【问题标题】:C Initialize a char array of a struct arrayC初始化struct数组的char数组
【发布时间】:2014-02-02 20:09:27
【问题描述】:

我不明白如何在数组结构中初始化 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数组给我带来了很多问题……

附: 我也尝试过使用

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

对于struct的其他字段也是这样的,但是这样我也报错了。

【问题讨论】:

    标签: c arrays struct char


    【解决方案1】:
    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)
    

    【讨论】:

    • 我总是使用 main() 并且它有效。现在我试试你的例子,然后我说你是否有效:)
    • 它在你的编译器上可能总是对你有用。但这是错误的。
    • 在我的学院里,我学会了以这种方式制作...... =S但是你的解决方案有效!非常感谢!
    • 有很多糟糕的教学正在进行。 main() 可能适用于您的编译器,但它是非标准的。你的老师应该教你int main(void)int main(int argc, char* argv[])
    【解决方案2】:

    还有其他解决方案。

    将你的 char 数组定义为 typedef,你可以像这样初始化你的数组。

    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 () { } 默认

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      相关资源
      最近更新 更多