int zippo[3][3] = { 5,6,7,8 };
printf("%d", zippo[0][3]);
如上代码所示,会打印8.也就是【0】【3】位置
但是
int zippo[3][3] = { 5,6,7,8 };
printf("%d", zippo[1][0]);
这一段代码,我的想法是因为数组里面的元素用完了,然后没有初始化的元素会赋予0,但是结果
依旧是8,为什么呀(⊙o⊙)?
int zippo[3][3] = { 5,6,7,8 };
printf("%d", zippo[0][3]);
如上代码所示,会打印8.也就是【0】【3】位置
但是
int zippo[3][3] = { 5,6,7,8 };
printf("%d", zippo[1][0]);
这一段代码,我的想法是因为数组里面的元素用完了,然后没有初始化的元素会赋予0,但是结果
依旧是8,为什么呀(⊙o⊙)?
收起
二维数组元素在内存是按行线性排列,即第一行元素之后紧接着是第二行元素。初始化二维数组时,如果你没有分组,那么就按初始化列表里的元素从第一行开始逐个初始化数组里的每个元素。
zippo[0][3]
等价于*((int*)&zippo + 0 * 3 + 3) = *((int*)&zippo + 3)
zippo[1][0]
等价于*((int*)&zippo + 1 * 3 + 0) = *((int*)&zippo + 3)
所以zippo[0][3]
和zippo[1][0]
都是指向数组中同一个元素。
https://en.cppreference.com/w/c/language/array_initialization#Nested_arrays
If the elements of an array are arrays, structs, or unions, the corresponding initializers in the brace-enclosed list of initializers are any initializers that are valid for those members, except that their braces may be omitted as follows:
If the nested initializer begins with an opening brace, the entire nested initializer up to its closing brace initializes the corresponding array element:
int y[4][3] = { // array of 4 arrays of 3 ints each (4x3 matrix)
{ 1 }, // row 0 initialized to {1, 0, 0}
{ 0, 1 }, // row 1 initialized to {0, 1, 0}
{ [2]=1 }, // row 2 initialized to {0, 0, 1}
}; // row 3 initialized to {0, 0, 0}
If the nested initializer does not begin with an opening brace, only enough initializers from the list are taken to account for the elements or members of the sub-array, struct or union; any remaining initializers are left to initialize the next array element:
int y[4][3] = { // array of 4 arrays of 3 ints each (4x3 matrix)
1, 3, 5, 2, 4, 6, 3, 5, 7 // row 0 initialized to {1, 3, 5}
}; // row 1 initialized to {2, 4, 6}
// row 2 initialized to {3, 5, 7}
// row 3 initialized to {0, 0, 0}
报告相同问题?