C语言10 多维数组

多维数组的定义

  1. 比如一个班有5个组,每个组有9个人

    int arr[45] 或者 intarr[5*9] 或者 int arr[5][9]

  2. 比如一个县有5个学校,每个学校有3个年级,每个年级有4个班,每个班有5个组,每个组有9个人

    int arr[53459] 或者int arr[5][3][4][5][9] int arr[5][3][4][5][9] ,又成为多维数组.

多维数组的初始化

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

多维数组的存储方式

int arr[3][4];

反汇编对比

8:        int arr[3*4] = {1,2,3,4,5,6,7,8,9,10,11,12};
00401028 C7 45 D0 01 00 00 00 mov         dword ptr [ebp-30h],1
0040102F C7 45 D4 02 00 00 00 mov         dword ptr [ebp-2Ch],2
00401036 C7 45 D8 03 00 00 00 mov         dword ptr [ebp-28h],3
0040103D C7 45 DC 04 00 00 00 mov         dword ptr [ebp-24h],4
00401044 C7 45 E0 05 00 00 00 mov         dword ptr [ebp-20h],5
0040104B C7 45 E4 06 00 00 00 mov         dword ptr [ebp-1Ch],6
00401052 C7 45 E8 07 00 00 00 mov         dword ptr [ebp-18h],7
00401059 C7 45 EC 08 00 00 00 mov         dword ptr [ebp-14h],8
00401060 C7 45 F0 09 00 00 00 mov         dword ptr [ebp-10h],9
00401067 C7 45 F4 0A 00 00 00 mov         dword ptr [ebp-0Ch],0Ah
0040106E C7 45 F8 0B 00 00 00 mov         dword ptr [ebp-8],0Bh
00401075 C7 45 FC 0C 00 00 00 mov         dword ptr [ebp-4],0Ch
10:       int arr[3][4] = {
11:           {1,2,3,4},
00401028 C7 45 D0 01 00 00 00 mov         dword ptr [ebp-30h],1
0040102F C7 45 D4 02 00 00 00 mov         dword ptr [ebp-2Ch],2
00401036 C7 45 D8 03 00 00 00 mov         dword ptr [ebp-28h],3
0040103D C7 45 DC 04 00 00 00 mov         dword ptr [ebp-24h],4
12:           {5,6,7,8},
00401044 C7 45 E0 05 00 00 00 mov         dword ptr [ebp-20h],5
0040104B C7 45 E4 06 00 00 00 mov         dword ptr [ebp-1Ch],6
00401052 C7 45 E8 07 00 00 00 mov         dword ptr [ebp-18h],7
00401059 C7 45 EC 08 00 00 00 mov         dword ptr [ebp-14h],8
13:           {9,10,11,12}
00401060 C7 45 F0 09 00 00 00 mov         dword ptr [ebp-10h],9
00401067 C7 45 F4 0A 00 00 00 mov         dword ptr [ebp-0Ch],0Ah
0040106E C7 45 F8 0B 00 00 00 mov         dword ptr [ebp-8],0Bh
00401075 C7 45 FC 0C 00 00 00 mov         dword ptr [ebp-4],0Ch
14:       };

通过观察我们发现,所谓多维数组和一维数组,在内存分配上完全相同

所以

int arr[3*4]  完全等价于  int arr[3][4]

使用多维数组的原因是,使用方便 寻找元素非常方便,在底层方面和一维数组没有任何的区别

多维数组的读写

比如:一年有12个月,每个月都有一个平均气温,存储5年的数据

int arr[5][12] = {
    {1,2,1,4,5,6,7,8,9,1,2,3}, //0
    {1,2,1,4,5,6,7,8,9,1,2,3}, //1
    {1,2,1,4,5,6,7,8,9,1,2,3}, //2
    {1,2,1,4,5,6,7,8,9,1,2,3}, //3
    {1,2,1,4,5,6,7,8,9,1,2,3}  //4
};

===
获取第一年第9个月的数据:
arr[0][8]
编译器是如何找到这个数据的:
arr[0*12+8]

===
获取第二年第8个月的数据:
arr[1][7]
编译器是如何找到这个数据的
arr[1*12+7]

多维数组的存储于读写

假设一共有5个班,每个班4个组,每组3个人

int arr5[3] = {

{{1,2,3},{4,5,6},{7,8,9},{11,12,14}},
{{11,12,13},{14,15,16},{17,18,19},{111,112,114}},
{{21,22,23},{24,25,26},{27,28,29},{211,212,214}},
{{31,32,33},{34,35,36},{37,38,39},{311,312,314}},
{{41,42,43},{44,45,46},{47,48,49},{411,412,414}},

};

编译器如何分配空间?

如果获取第2个班级、第3组、第2个人的年龄: arr[1][2][1]
编译器的计算: arr[1*4*3 + 2*3 + 1]

如果获取第4个班级、第4组、第3个人的年龄: arr[3][3][2]
编译器如何计算?

arr[3*4*3 + 3*3 + 3]
updatedupdated2024-10-152024-10-15