要初始化一个二维数组,通常我们可以这样做:
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/