我从int x得到了一个非常奇怪的输出[3];

New*_*ner -1 c++ initialization

所以我在C++中键入下面的代码

#include <iostream>
using namespace std;
int main() {
    int x[3];
    cout << x[1] << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它打印出-272632344而不是0.任何理由?

son*_*yao 6

默认初始化

如果T是数组类型,则数组的每个元素都是默认初始化的;

然后

否则,什么都不做:具有自动存储持续时间的对象(及其子对象)被初始化为不确定值.

试图打印出这些不确定的值会导致未定义的行为.

如果您希望将所有元素初始化为零,则可能需要聚合初始化,例如

int foo [3] = {}; // all the elements will be value-initialized to zero
int foo [3] {};   // same as above
Run Code Online (Sandbox Code Playgroud)