How to initialize all fields of a structure when one of the fields is an array?

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

In the above code, I am trying to initialize the abc_t structure. Compiling the above code as:

 gcc -Wall sample.c 

gives me:

 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') 

How to avoid this warning?

+4
source share
4 answers

Try the following:

 abc_t abc ={0,1,{{{{0,0,0}}}}}; 
+2
source

Struct abc_t has a different structure inside the asd_field_t type, which you initialize to 0 using {0}. The warning you get from GCC is that you reset all members of this structure (asd_field), rather than filling them out one at a time. There is an argument that this behavior of GCC is incorrect, given that the standard considers it to be valid for zero the whole structure using {0}. You can read the GCC bug report here

You can also turn off the annoying warning by passing the -Wno-missing-braces option so you get all the other warnings on the wall, gcc -Wall -Wno-missing-braces test.c -o test .: gcc -Wall -Wno-missing-braces test.c -o test

+5
source

Well, you have to embed arrays in your abc_t structure, so you need to do something like:

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

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

-1
source

All Articles