整数数组[30] = {0};这在 c 中是如何工作的?

int array[30] = {0}; How this works in c?

这是如何工作的(将所有值设置为 0)?

int array[28]= {0};

为什么这不起作用(没有将所有值设置为 4,但只有第一个值设置为 4,其他值设置为 0)?

int array[28]= {4};

在 C 中,任何未在初始化程序中列出的元素都被隐式初始化为其零值。

int array[28]= {0}; 创建一个包含 28 个整数的数组,并将第一个元素初始化为 0。初始化程序中未提及的其余元素获取它们的零值,对于整数为 0。

int array[28]= {4}; 工作原理类似。第一个元素初始化为 4,其余未在初始化器中提及的元素获得它们的零值。

未初始化的元素设置为 0。在您的第一种情况下,您通过为它提供值 0 来初始化它,其余的默认初始化为 0。在您的第二种情况下,第一个值初始化为 4其余为 0。标准说:

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.

int array[5] = {0}

所有元素将被初始化为0

int array[5] = {1,2,3}

在这种情况下,第一个元素将被初始化为 1,第二个元素将被初始化为 2,第三个元素将被初始化为 3,其余元素将被初始化为 0。

仅仅是因为标准要求它。

ISO/IEC:9899(c99 标准)TC3 声明:

6.7.8 Initialization

[...]

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.

第 10 点指的是同一段落: (强调我的)

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. 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.

所以简单地假设这必须发生,这就是它发生的原因。