C 语言中的多维数组

C 语言中的多维数组与我们在数学中学习到的多维数组是一致的。如果你还不知道什么是多维数组也没有关系。多维数组可以看成是之前学习过的数组的扩展。它能让你完成一些仅仅依靠一维数组没有办法完成的事情。让很多事情完成的更为简单。

1. 多维数组的声明

``````int intArray[A1][A2][A3][...][An]
``````
``````int intArray[2][2];  // 二维数组
float floArtay[3][4][5]; // 三维数组
``````

``````int intArray[][5][3]
``````

2. 多维数组初始化

``````short a[2][2] = { 1, 2, 3, 4};
short b[2][2] = { {1, 2}, {3, 4}};
short c[2][2] = { 3, 4};
short d[2][2] = { {}, {3, 4}};
``````

4. 示例

``````#include <stdio.h>

int main()
{
short a[2][2] = {{}, {3, 4}};
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("a[%d][%d] = %d\n", i, j, a[i][j]);
}
}

int b[][2] = {{1, 2}, {3, 4}};
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("b[%d][%d] = %d\n", i, j, b[i][j]);
}
}

int c[3][2][2] = {{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}},
{{9, 10}, {11, 12}}};

for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
printf("c[%d][%d][%d] = %d\n", i, j, k, c[i][j][k]);
}
}
}

return 0;
}
``````

``````a[0][0] = 0
a[0][1] = 0
a[1][0] = 3
a[1][1] = 4
b[0][0] = 1
b[0][1] = 2
b[1][0] = 3
b[1][1] = 4
c[0][0][0] = 1
c[0][0][1] = 2
c[0][1][0] = 3
c[0][1][1] = 4
c[1][0][0] = 5
c[1][0][1] = 6
c[1][1][0] = 7
c[1][1][1] = 8
c[2][0][0] = 9
c[2][0][1] = 10
c[2][1][0] = 11
c[2][1][1] = 12
``````