簡體   English   中英

C初始化結構體數組的char數組

[英]C Initialize a char array of a struct array

我不明白如何在數組結構中初始化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};
}

但是當我編譯時,它告訴我在'{'之前需要一個表達式。 我該如何解決? 這些char數組給我帶來很多問題...

PS Ive也嘗試使用

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

並以這種方式用於struct的其他字段,但是以這種方式我有一個錯誤。

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)

還有另一種解決方案。

將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}
};

在預處理時,編譯器將能夠初始化數組

大衛·赫弗曼的回應

您的寫作嘗試

biblio [0] .titolo =“ Guida al C”; 失敗,因為您無法分配給字符數組。 您必須初始化它們,或使用類似strcpy的函數。

為了更好地解釋,您必須在正確的存儲區中初始化每個角色。

例如

biblio [0] .titolo =“ Guida al 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:main(){}

gcc默認會自動將int main(){}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM