为什么每个值都没有初始化为0?

#include <stdio.h>

int main(void) {
    int memo[1000];
    for (int i = 0; i < 1000; i++) {
        printf("%dt", memo[i]);
    }
    return 0;
}

我认为一切都应该初始化为 0 但事实并非如此。这有什么原因吗?非常感谢你的帮助。

回答

本地定义并自动存储在函数体中的对象在 C中未初始化。这些值可以是任何东西,包括某些体系结构上的陷阱值,这些值仅通过读取它们就会导致未定义的行为。

您可以将此数组初始化为int memo[1000] = { 0 };. 第一个元素被显式初始化为0,其余0所有元素也将被初始化为 ,因为任何缺少初始化器的元素都将被设置为0

为完整起见,int memo[1000] = { 42 };将其第一个元素设置为42,其余所有元素设置为0。类似地,C99 初始值设定项int memo[1000] = { [42] = 1 };将其第 43 个元素设置为1并且所有其他元素都设置为0

  • @CEPB: Yes, K&R C didn't allow auto arrays to be initialized (see K&R I page 83). This was roughly in keeping with the philosophy that every line of code should be O(1) (e.g. you couldn't assign structs or pass them by value either, because this might require copying arbitrarily large blocks of memory). C89 footnote 65 explicitly noted that the ability to initialize all auto objects was new.

以上是为什么每个值都没有初始化为0?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>