如何用?初始化结构数组?(How to initialize array of structures with?)

编程入门 行业动态 更新时间:2024-10-25 22:31:41
如何用?初始化结构数组?(How to initialize array of structures with?) struct SampleStruct { int a; int b; float c; double d; short e; };

对于像这样的数组,我曾经用它初始化如下:

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.

更多推荐

本文发布于:2023-07-23 00:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1225229.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   初始化   如何用   结构   structures

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!