堆栈分配的数组是否会自动零初始化?

Kar*_*los 0 c++

如果我做这样的事情:

int myArray[5];
Run Code Online (Sandbox Code Playgroud)

该数组是否自动零初始化?如果不是,我如何声明一个堆栈分配、零初始化的数组?

我知道对于堆分配的数组,我可以这样做:

int* myArray = new int[5]();
Run Code Online (Sandbox Code Playgroud)

不管怎么说,还是要谢谢你 :)

小智 6

不,数组的初始值是未初始化的值(即未定义)。在 C++ 中它们不会被初始化为零;

要将数组显式初始化为零,可以使用以下语法:

int myarray[5]{};      // Yes it would be nice to use int myarray[5]();
                       // Like you did with dynamic allocation.
                       // But of course the most vexing parse kicks in
                       // So we added '{}` as an alternative to `()`
                       // to get around this small issues.

// Of course there are a couple of alternatives
// From the original syntax.
int myarray[5]={0};    // From: C (paraphrasing)
                       // If the list of values in an array
                       // initializer is not long enough for the
                       // array it is expanded with 0 to
                       // make sure the list matches the length
                       // of the array.
Run Code Online (Sandbox Code Playgroud)

这是 C++ 中将数组元素初始化为零的标准方法;

希望这能回答您的问题。

  • C++ 不是 C,“{0}”可以是“{}”。甚至更短的 `int myarray[5]{};` (2认同)