空白初始化C99中的结构数组 [英] Blank initialising an array of structs in C99

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

问题描述

这似乎是我所学的一个漏洞。据我所知,在C99中,如果您初始化结构的单个元素而没有其他元素,则其他元素将被初始化为零。下列代码是否将结构的所有成员初始化为零?

This seems like a hole in my knowledge. As far as I am aware, in C99 if you initialise a single element of a struct and no others, the others are zero initialised. Does the following code zero initialise all the members of a struct though?

typedef struct
{
    int foo;
    int bar;
    char* foos;
    double dar;
} some_struct_t;

some_struct_t mystructs[100] = {};

更新:有些注释表明此语法是扩展名。如果是这样,有没有办法做到完全符合C99?

Update: There are some comments indicating that this syntax is an extension. If that is the case, is there any way of doing this that is pure C99 compliant?

推荐答案

C11 ,第§6.7.9章,初始化语法,(出于完整性考虑,,与 C99

As per C11, chapter §6.7.9, Initialization syntax, (for the sake of completeness, same mentioned in chapter §6.7.8 in C99)


初始化器:

    赋值表达式

        " {初始值设定项列表}

     {initializer-list,}

      assignment-expression
      { initializer-list }
      { initializer-list , }

initializer-list:

    指定 opt 初始化程序

         initializer-list,名称 opt 初始化程序

initializer-list:
      designationopt initializer
      initializer-list , designationopt initializer

名称:

      指示符-list =

designation:
      designator-list =

指示符列表:

     &nbs p;指示符

     指示符列表指示符

designator-list:
      designator
      designator-list designator

指示符:

     [恒定表达式]

       。标识符

designator:
      [ constant-expression ]
      . identifier

这意味着,括号封闭的初始值设定项列表应至少包含一个初始值设定项元素(对象)。

Which implies, the brace closed initializer list should have at minimum one initializer element (object).

在您的代码中,空的初始化程序列表

In your code, the empty initializer list

 some_struct_t mystructs[100] = {};  //empty list

不是有效的纯C语法;

is not a valid pure C syntax; it's a compiler extension.

您需要在列表中提及单个元素以使其符合标准,例如

You need to mention a single element in the list to make it standard conforming, like

some_struct_t mystructs[100] = {0};


$ b

which meets the criteria, from paragraph 21 of same standard(s),


如果用大括号括起来的列表中的初始化程序少于元素或成员总数中的
,或更少字符串文字中的字符,用于初始化一个已知
大小的数组,而不是该数组中的元素,集合的其余部分应隐式初始化为
,与具有静态存储持续时间的对象相同

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

因此,在这种情况下,您有一个显式0并保留了隐式零初始化(或类似的初始化)。

So, in this case, you have one explicit 0 and remaining implicit zero-initialization (or similar).

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

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