对于像这样的数组,我曾经用它初始化如下:
struct SampleStruct sStruct = {0};我想知道当我声明这个结构的数组时,我认为这是正确的
struct SampleStruct sStructs[3] = {{0},{0},{0}};但是,下面也被编译器接受了
struct SampleStruct sStructs[3] = {0};我想知道最好,最安全的方法和详细原因。
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)如果使用-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]指示您应该为初始化编写= {{0}} ,这会将第一个结构的第一个字段设置为0,并将所有其余字段隐式设置为0。 该程序在这个简单的情况下给出了正确的结果,但我认为你不应该依赖于这个并且需要正确地初始化事物。
$ 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.
更多推荐
发布评论