C语言初始化二维数组的问题


    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}

zippo[0][3]不就是zippo[1][0]么,试试zippo[1][1]
int zippo[3][3] 下标范围0-2.

因为你这样写二维数组,它没有正常识别每行每列的元素
zip[0][3] 是0行3列


zip[1][0] 是1行0列
输出都是8是正常的,因为它无法正常识别这样初始化的二维数组


可参考初始化方法:

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

希望对题主有所帮助!可以的话,帮忙点个采纳!