C中结构数组的部分初始化

Partial initialization for an array of structures in C

在复习我的C知识时,我无意中遇到了下面的例子:

#include <stdio.h>

/* Just a simple structure */
typedef struct lab {
    int num;
    char *str;
} bal;

int main (void) {
    /* Declare and _partially_ initialize an array of the structure above... */
    bal struct_array[10] = { {0, NULL} };

    /* Question: what does _exacly_ happen to the other 9 members of the array? */ 
    return 0;
};

代码中的注释应该足以提供我的问题。换句话说,如果我们部分初始化一个结构数组会发生什么?当然,我知道(至少)对于 C++11 有默认初始化。但它也适用于纯 C 吗?如果是,是否适用于所有标准(从 C89 开始),还是仅适用于某些标准?谢谢。

如果数组或结构仅被部分初始化,则任何包含没有显式初始化程序的对象都将设置为 0 或 NULL。

C11 standard:

的第 6.7.9p21 节介绍了部分初始化

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.9p10 节介绍了具有静态存储持续时间的对象的初始化:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread 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,and any padding is initialized to zero bits;
  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits

因此在您的特定情况下,所有数组元素都将 num 成员设置为 0,str 成员设置为 NULL。