开天辟地的卷毛 2022-03-18 23:45 采纳率: 85.4%
浏览 34
已结题

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⊙)?

  • 写回答

3条回答 默认 最新

  • _GX_ 2022-03-19 00:38
    关注

    二维数组元素在内存是按行线性排列,即第一行元素之后紧接着是第二行元素。初始化二维数组时,如果你没有分组,那么就按初始化列表里的元素从第一行开始逐个初始化数组里的每个元素。

    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}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 5月1日
  • 已采纳回答 4月23日
  • 创建了问题 3月18日

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错