How to initialize array of structures with?

无人久伴 提交于 2019-12-23 17:25:29

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/8570707/how-to-initialize-array-of-structures-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!