How to initialize an array of structures with?

struct SampleStruct {
   int a;
   int b;
   float c;
   double d;
   short e;       
};

For such an array, I used it to initialize, as shown below:

struct SampleStruct sStruct = {0};

I would like to know when I declare an array of this structure, I thought it would be correct

struct SampleStruct sStructs[3] = {{0},{0},{0}};

But, below is also accepted by the compiler

struct SampleStruct sStructs[3] = {0};

I would like to know the best and safest way and the detailed reason why this is so.

+3
source share
2 answers
$ gcc --version
gcc (GCC) 4.6.1 20110819 (prerelease)

If you use the option -Wall, my gcc gives me warnings about the third:

try.c:11:9: warning: missing braces around initializer [-Wmissing-braces]
try.c:11:9: warning: (near initialization forsStruct3[0]’) [-Wmissing-braces]

indicating what you should write = {{0}}for initialization, which set the first field of the first structure to 0, and everything else - 0 implicitly. The program gives the correct result in this simple case, but I think you should not rely on it and you should properly initialize things.

+4

gcc-4.3.4 , .

struct SampleStruct sStruct1 = {0}; , 0 a. .

struct SampleStruct sStructs2[3] = {{0},{0},{0}}; , , , "" . .

struct SampleStruct sStructs3[3] = {0}; , -, , - .

+1

All Articles