2014-01-14 43 views
0

我無法理解如何初始化數組struct中的char數組。我寫了這樣的代碼:C初始化struct數組的char數組

typedef struct tomo 
{ 
    char titolo[100]; 
    char autore[100]; 
    int anno_pubblicazione; 
    float prezzo; 
} t_libro; 

main(){ 
    t_libro biblio[2]; 
    biblio[0] = {"Guida al C", "Fabrizio Ciacchi", 2003, 45.2}; 
    biblio[1] = {"Harry Potter e la Pietra Filosofale", "J.K.Rowling", 2003, 12.5}; 
} 

但是當我編譯時,它說我在'{'表達式是預期的。 我怎麼能解決它?這些字符陣列給我很多問題...

P.S. 我用盡也使用

biblio[0].titolo = "Guida al C"; 

,並以這種方式爲結構的其他領域,也以這種方式我有一個錯誤。

回答

8
biblio[0] = {"Guida al C", "Fabrizio Ciacchi", 2003, 45.2}; 

這不是初始化。這是一個簡單的任務。您只能在初始化中使用初始化語法。它看起來像這樣:

t_libro biblio[] = { 
    {"Guida al C", "Fabrizio Ciacchi", 2003, 45.2}, 
    {"Harry Potter e la Pietra Filosofale", "J.K.Rowling", 2003, 12.5} 
}; 

你嘗試寫,因爲你不能分配到字符數組

biblio[0].titolo = "Guida al C"; 

失敗。您必須初始化它們,或者使用像strcpy這樣的函數。

您的main聲明也是錯誤的。它應該是

int main(void) 
+0

我總是用main()和它的作品。現在我嘗試你的例子,然後我說你是否工作:) – ProtoTyPus

+2

它可能總是適合你的編譯器。但這是錯誤的。 –

+0

在我的學院已經學會了我以這種方式進行...... = S 但是,您的解決方案的工作原理!非常感謝你! – ProtoTyPus

1

還有一種解決方案。

將您的char數組定義爲typedef,並且您可以像這樣初始化您的Array。

typedef char T_STRING[100] ; 

typedef struct tomo 
{ 
    T_STRING titolo; 
    T_STRING autore; 
    int anno_pubblicazione; 
    float prezzo; 
} t_libro; 

t_libro biblio[] = { 
    {"Guida al C", "Fabrizio Ciacchi", 2003, 45.2}, 
    {"Harry Potter e la Pietra Filosofale", "J.K.Rowling", 2003, 12.5} 
}; 

在預處理找你的編譯器將能夠初始化數組

從大衛Hefferman的respons

你嘗試寫

文獻記錄[0] .titolo =「Guida al C」;因爲您不能分配到 字符數組,因此失敗。您必須初始化它們,或者使用像strcpy這樣的函數 。

爲了更好地解釋,您必須在正確的內存區域中初始化每個caractere。

例如

文獻記錄[0] .titolo = 「貴大人C」; 必須在內存中工作良好:

biblio[0].titolo[0] = 'G'; 
biblio[0].titolo[1] = 'u'; 
biblio[0].titolo[2] = 'i'; 
biblio[0].titolo[3] = 'd'; 
biblio[0].titolo[4] = 'a'; 
biblio[0].titolo[5] = ' '; 
biblio[0].titolo[6] = 'a'; 
biblio[0].titolo[7] = 'l'; 
biblio[0].titolo[8] = ' '; 
biblio[0].titolo[9] = 'C'; 
biblio[0].titolo[0] = '\0'; // (don't forget to initialize the end of your string) 

這是什麼的strcpy(或strncpy()函數)做的非常好。

PS:主要(){}

GCC會自動把 INT的main(){}默認