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

pan*_*naj 4 c gcc-warning data-structures

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

gcc -Wall sample.c
Run Code Online (Sandbox Code Playgroud)

给我:

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')
Run Code Online (Sandbox Code Playgroud)

我该如何避免这种警告?

the*_*ole 5

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

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