Linux C 编程教程第 24 部分 - 多维数组
在此页
- C 中的多维数组
- 结论
如果您遵循这个正在进行的数组概念。为了快速刷新,数组用于连续存储多个相同类型的值。
C 中的多维数组
例如,以下是一个能够存储 5 个数字的整数数组。
int arr[5]
存储在数组中的任何值都可以使用数组名称和相应的索引值轻松访问。由于索引从 0 开始,假设你想访问数组中的第二个元素,你可以通过以下方式进行:
arr[1]
下面的程序接受来自用户的 5 个整数作为输入,将它们存储在一个数组中,然后将它们输出回给用户。
#include <stdio.h>
int main()
{
int arr[5],i;
printf("Enter 5 integer values\n");
for(i=0;i<5;i++)
scanf("%d",&(arr[i]));
printf("You entered the following values:\n");
for(i=0;i<5;i++)
printf("%d\n",arr[i]);
return 0;
}
现在,这种类型的数组被称为一维数组。是的,这意味着还存在多维数组——二维数组、三维数组等等。例如,下面是一个二维数组:
int arr[2][3]
您可以将此数组可视化为具有 2 行和 3 列的二维数字表 - 如下所示:
x x x
x x x
所以这个数组总共可以容纳 6 个元素。值得一提的是,数组可以容纳的元素总数可以通过乘以数组声明中的索引轻松计算出来。例如,对于 arr,数组的容量可以通过 2x3 计算得出,等于 6。
来到初始化部分,像 arr 这样的二维数组可以通过以下方式初始化:
int arr [2][3] = {1,2,3,4,5,6}
由于上述初始化使得很难在二维数组中可视化这些值,因此您可以选择另一种(阅读:更好的)方法。这里是:
int arr [2][3] = { {1,2,3}, {4,5,6} };
所以现在很容易想象数字 1、2、3 在一行中,而 4、5、6 在另一行中。干得好:
1 2 3
4 5 6
至于如何在C中处理二维数组,下面是一个小程序,它从用户那里接受这6个值,将它们存储在一个二维数组arr中,最后将它们输出回给用户:
#include <stdio.h>
int main()
{
int arr[2][3],i,j;
printf("You are about to enter values for a 2x3 array\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\n Enter value to be stored at row %d and column %d :: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n You entered the following values:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\n Row %d and column %d = %d\n",i,j,arr[i][j]);
}
}
return 0;
}
这是输出:
You are about to enter values for a 2x3 array
Enter value to be stored at row 0 and column 0 :: 1
Enter value to be stored at row 0 and column 1 :: 2
Enter value to be stored at row 0 and column 2 :: 3
Enter value to be stored at row 1 and column 0 :: 4
Enter value to be stored at row 1 and column 1 :: 5
Enter value to be stored at row 1 and column 2 :: 6
You entered the following values:
Row 0 and column 0 = 1
Row 0 and column 1 = 2
Row 0 and column 2 = 3
Row 1 and column 0 = 4
Row 1 and column 1 = 5
Row 1 and column 2 = 6
以上就是关于二维数组的一些基本信息。 3-D 数组呢?那么,在同一行中,您也可以定义和初始化三维数组。这是一个例子:
int arr[2][3][4]
那么如何可视化这个数组呢?好吧,想想一个三维世界(我们生活的世界),然后想象三个相互垂直的维度。这就是这个数组的三个维度如何适应的。
携带24个元素(2x3x4)的容量,这个数组可以通过以下方式初始化:
int x[2][3][4] =
{
{ {1,2,3,4}, {5,6,7,8}, {9,10,11,12} },
{ {13,14,15,16}, {17,18,19,20}, {21,22,23,24} }
};
这是一个使用 3-D 数组的 C 程序:
#include <stdio.h>
int main()
{
int arr[2][3][4],i,j,k;
printf("You are about to enter values for a 2x3x4 array\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<4;k++)
{
printf("\n Enter value to be stored at arr[%d][%d][%d] :: ",i,j,k);
scanf("%d",&arr[i][j][k]);
}
}
}
printf("\n You entered the following values:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<4;k++)
{
printf("\n arr[%d][%d][%d] = %d\n",i,j,k,arr[i][j][k]);
}
}
}
return 0;
}
结论
在本教程中,我们通过讨论多维数组的概念扩展了我们对数组的现有理解。建议您在您的系统上尝试本教程中使用的示例(以及创建新示例)以更好地了解这些数组的工作原理。如有任何疑问或疑问,请在下方发表评论。