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

For an array like this, I used to initialize it as below:

struct SampleStruct sStruct = {0};

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

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

But, below also got accepted by the compiler

struct SampleStruct sStructs[3] = {0};

I would like to know the best and safe way and detailed reason why so.

San
  • 3,933
  • 7
  • 34
  • 43
  • 1
    Please tell us exactly what error you get, and exactly what compiler you use. "It gives me an error" is about as clear as mud. – Mike Nakis Dec 19 '11 at 17:14

2 Answers2

4
$ gcc --version
gcc (GCC) 4.6.1 20110819 (prerelease)

If using -Wall option, my gcc gives me warnings about the third one:

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

indicating that you should write = {{0}} for initialization, which set the first field of the first struct to 0 and all the rest to 0 implicitly. The program gives correct result in this simple case, but I think you shouldn't rely on this and need to initialize things properly.

pjhades
  • 1,948
  • 2
  • 19
  • 34
1

gcc-4.3.4 does not give an error with the first two declarations, while it gives an error with the third.

struct SampleStruct sStruct1 = {0}; works because 0 in this case is the value of field a. The rest of the fields are implicitly initialized to zero.

struct SampleStruct sStructs2[3] = {{0},{0},{0}}; works because what you are doing here is declaring three structs and initializing field 'a' of each one of them to zero. The rest of the fields are implicitly initialized to zero.

struct SampleStruct sStructs3[3] = {0}; does not work, because within the curly brackets the compiler expects to see something that corresponds to three structures, and the number zero just is not it.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • The funny thing is, I went now to ideone.com to try this again in order to add more information about the error I am getting, and it all compiles without any error. I suppose the warning level has changed at ideone, but I have no control over it. – Mike Nakis Dec 20 '11 at 14:50