如何初始化结构数组? [英] How to initialize array of structures with?

查看:57
本文介绍了如何初始化结构数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 会给我关于第三个的警告:

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]

表示您应该编写 = {{0}} 进行初始化,这会将第一个结构的第一个字段设置为 0,其余所有字段都隐式设置为 0.程序在这个简单的情况下给出了正确的结果,但我认为你不应该依赖这个,需要正确地初始化.

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.

这篇关于如何初始化结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆