2013-05-26 25 views
-1

有誰知道爲什麼下面的代碼不適用於char?它的工作原理與int秒,但我想用char初始化結構失敗,並給出類似的警告:使用char來初始化結構的函數 - 解釋我的警告?

warning: assignment makes integer from pointer without a cast 

我不知道這是什麼警告裝置。

#include <stdio.h> 
#include <stdlib.h> 

struct complex { 
int re; 
int im; 
char name; 
}; 

struct complex initialize (int k, int l, char nazwa) 
{ 
    struct complex x; 
    x.re = k; 
    x.im = l; 
    x.name= nazwa; 
    return x; 
} 


int main() 
{ 
    struct complex e; 
    struct complex f; 
    int a; 
    int b; 
    char o; 
    int c; 
    int d; 
    char p; 
    a=5; 
    b=6; 
    o="t"; 
    e = initialize (a, b, o); 
    c=8; 
    d=3; 
    p="u"; 
    f=initialize (c, d, p); 
    printf("c1 = (%d,%d)\nc2 = (%d,%d)\n name 1=%s name 2=%s\n", e.re , e.im, f.re, f.im, e.name, f.name); 

    return 0; 
} 
+2

你不能說'o =「t」'你需要說'o ='t''。你的問題似乎與一個結構甚至一個函數無關。 –

+0

使用「rb」/「wb」標誌和「char」而不是「const char *」。但這是一個新問題。 – Elazar

回答

5

"u"不是字符。它是一個字符串。一個char數組。您需要改爲'u'。但是,那麼您將只有一個字符的名稱,並且您將需要用%c替換printf中的%s

除非你真的想要一個字符串,並且如果是這樣,請將結構中的char更改爲const char*。功能參數相同:

struct complex { 
    int re; 
    int im; 
    const char* name; 
}; 

struct complex initialize (int k, int l, const char* nazwa) { 
... 
} 

const char* o; 
const char* p; 

請注意,您可以初始化變量和結構。你的代碼可以是這樣的:

void print_complex(int n, struct complex c) { 
    printf("c %d = (%d,%d)\n", n, c.re , c.im); 
    printf("name=%s\n", c.name); 
} 

int main() { 
    struct complex e = { 5, 6, "t" }; 
    struct complex f = { 8, 3, "u" }; 
    print_complex(1, e); 
    print_complex(2, f); 
    return 0; 
} 
+0

我嘗試了兩種方式,用字符串和字符,程序copmpiles,但仍然停止工作,並剎車停下來 – Pepasek

+0

@Pepasek如果你將改變每個'char''const char *'它應該工作。 – Elazar

+0

現在感謝它的工作:)但如何將這些結構存儲在文件中?現在我有一個與此: FILE * fp = fopen(「doc.txt」,「a +」); fwrite(&e,sizeof(e),1,fp); fwrite(&f,sizeof(e),1,fp); fclose(fp); fopen(「doc.txt」,「r」); (&e,sizeof(e),1,fp); printf(「%d%d%s \ n」,e.re,e.im,e.name); (&f,sizeof(e),1,fp); 012fprintf(「%d%d%s \ n」,f.re,f.im,f.name); fclose(fp); – Pepasek