简体   繁体   English

如何用?初始化结构数组?

[英]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: 如果使用-Wall选项,我的gcc会给出关于第三个的警告:

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. 表示你应该写= {{0}}进行初始化,它将第一个结构的第一个字段设置为0,其余部分隐式设置为0。 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. gcc-4.3.4不会给前两个声明带来错误,而它会给第三个声明带来错误。

struct SampleStruct sStruct1 = {0}; works because 0 in this case is the value of field a . 有效,因为在这种情况下0是字段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. 因为你在这里所做的是声明三个结构并将每个结构的字段'a'初始化为零而起作用。 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. 不起作用,因为在大括号内编译器期望看到对应于三个结构的东西,而数字零不是它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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