c - 全局初始化数组的未使用索引?

标签 c arrays c99

我有一个结构数组。只需要初始化几个索引位置。是否有一个编译器属性可以确保未初始化的组合被初始化为 0?

例如:

如果我有一个如下所示的静态初始化结构数组,如何确保该数组中剩余的 3 个元素(未明确预初始化)被清零?

typedef struct foo_s {
    int a;
    int b;
} foo_t;

foo_t foo_array[4] = {
    { .a = 1, .b = 2 },
};

谢谢

最佳答案

您想要的行为已经是标准 C 的一部分。不存在“半初始化”变量;如果您只初始化某些内容的一部分,那么所有剩余元素都将被零初始化。

此外,您(在标题中)说该数组是全局的。这意味着它具有静态存储持续时间,因此即使您根本不提供任何初始化程序,它也将被零初始化。

在聚合初始值设定项上引用 C99:

6.7.8/19:

[...] all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

6.7.8/21:

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.

6.7.8/10:

If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

关于c - 全局初始化数组的未使用索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46876451/

相关文章:

c - 使用常量值时部分宏被优化掉

c - C 中指向数组的指针

c - 使用分隔符分隔字符串和整数

Java访问字符串数组中的特定元素

C++ fast-cpp-csv-parser 到数组

C99条件返回值

C 代码在 64 位 Ubuntu 14.04 中有效,但在 32 位 Ubuntu 14.04 中失败

c++ - 如何将 QString 或 QStringList 传递给 QTableWidgetItem

做指针事情时的 Const 类型限定符

c - 为什么我们需要在 C 中使用函数之前声明它们?