简体   繁体   中英

How to initialize array of structures with?

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.

$ 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM