当其中一个字段是数组时,如何初始化结构的所有字段?

时间:2013-03-26 09:17:07

标签: c data-structures gcc-warning

#include <stdio.h>

typedef struct
{
    int as;
    int bs;
    int cs;
}asd_t;

typedef struct
{
    asd_t asd[10];
}asd_field_t;    

typedef struct
{
    int a;
    int b;
    asd_field_t  asd_field[10];
}abc_t;    

int main()
{
    abc_t abc ={0,1,{0}};
    return 0;
}

在上面的代码中,我试图初始化结构abc_t。将上面的代码编译为:

gcc -Wall sample.c

给了我:

sample.c: In function 'main':
sample.c:26: warning: missing braces around initializer
sample.c:26: warning: (near initialization for 'abc.asd_field[0].asd')

如何避免此警告?

4 个答案:

答案 0 :(得分:5)

struct abc_t在asd_field_t类型中有另一个结构,你使用{0}初始化为0。您从GCC获得的警告是因为您将该结构的所有成员(asd_field)归零,而不是逐个填充它们。有一个论点认为GCC的这种行为是不正确的,因为标准认为使用{0}将整个结构归零是完全有效的。您可以阅读GCC的错误报告here

您还可以通过传递选项-Wno-missing-braces来禁用恼人的警告,以便获得所有其他墙警告,即: gcc -Wall -Wno-missing-braces test.c -o test

答案 1 :(得分:2)

试试这个:

abc_t abc ={0,1,{{{{0,0,0}}}}};

答案 2 :(得分:0)

嗯,您必须在结构abc_t中嵌套数组,因此,您必须执行以下操作:

abc_t abc = {0,1,{{0,0,0}}};

答案 3 :(得分:-1)

abc_t abc = {0,1,{{{{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0 ,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}}},{{{0 ,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0 ,0},{0,0,0},{0,0,0},{0,0,0}}},{{{0,0,0},{0,0,0},{0 ,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0 ,0},{0,0,0}}},{{{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0 ,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}}},{{ {0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0 ,0,0},{0,0,0},{0,0,0},{0,0,0}}},{{{0,0,0},{0,0,0}, {0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0 ,0,0},{0,0,0}}},{{{0,0,0},{0,0,0},{0,0,0},{0,0,0}, {0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}}}, {{{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}, {0,0,0},{0,0,0},{0,0,0},{0,0,0}}},{{{0,0,0},{0,0,0 },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}, {0,0,0},{0,0,0}}},{{{0,0,0},{0,0,0},{0,0,0},{0,0,0 },{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}} }};