c++ - 二维数组的意外初始化结果

标签 c++ arrays initialization

要初始化一个二维数组,通常我们可以这样做:

int matrix[3][4] = { {1,1,1,1}, {2,2,2,2}, {3,3,3,3} };

但是,当我用各种组合对其进行测试时,以下代码确实编译出了我的预期:

int matrix[3][4] = {1,2,3,4,5,6,7};

当我以二维表格形式打印输出时,我得到:

1,2,3,4,
5,6,7,0,
0,0,0,0,

我明白为什么其余的值为零。

我的问题是:这是通过假设超出行边界的数字总是“流”到下一行来初始化二维数组的合法方法之一吗?或者这是我应该在 C++ 中避免的另一个陷阱?

最佳答案

是的,这非常好。引用 the unofficial cppreference :

The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

和:

If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are initialized by empty lists, which performs value-initialization.

int 的初始化值将其设置为 0

关于c++ - 二维数组的意外初始化结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36959697/

相关文章:

C++ vector 模板参数 1 无效

c - 如何计算数组的元素个数

c++ - 非常量引用的初始化

swift 2.2 : failable initializers in lazy properties

javascript - 范围过滤和数组数组拼接

C - 在循环中创建结构成员?

c++ - 什么时候值得使用数据库?

c++ - 如何比较两个 std::istream 引用?

c++ - OpenGL3 SFML 2.0rc FPS 风格的相机 - 鼠标移动不稳定

javascript - 如何使用 jquery 处理数组