# C/C++中如何使用多维数组？解析和用法示例

2021年3月31日17:51:18 发表评论 424 次浏览

``````data_type  array_name[size1][size2]....[sizeN];

data_type: Type of data to be stored in the array.
Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2, ... , sizeN: Sizes of the dimensions``````

``````Two dimensional array:
int two_d[10][20];

Three dimensional array:
int three_d[10][20][30];``````

### 二维数组

``````data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.``````

``int x[3][4] = {0, 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}``

``int x[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};``

``int x[2][1];``

``````// C++ Program to print the elements of a
// Two-Dimensional array
#include<iostream>
using namespace std;

int main()
{
// an array with 3 rows and 2 columns.
int x[3][2] = {{0, 1}, {2, 3}, {4, 5}};

// output each array element's value
for ( int i = 0; i < 3; i++)
{
for ( int j = 0; j < 2; j++)
{
cout << "Element at x[" << i
<< "][" << j << "]: " ;
cout << x[i][j]<<endl;
}
}

return 0;
}``````

``````Element at x[0][0]: 0
Element at x[0][1]: 1
Element at x[1][0]: 2
Element at x[1][1]: 3
Element at x[2][0]: 4
Element at x[2][1]: 5``````

### 三维数组

``int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23};``

``````int x[2][3][4] =
{
{ {0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11} }, { {12, 13, 14, 15}, {16, 17, 18, 19}, {20, 21, 22, 23} }
};``````

``````// C++ program to print elements of Three-Dimensional
// Array
#include<iostream>
using namespace std;

int main()
{
// initializing the 3-dimensional array
int x[2][3][2] =
{
{ {0, 1}, {2, 3}, {4, 5} }, { {6, 7}, {8, 9}, {10, 11} }
};

// output each element's value
for ( int i = 0; i < 2; ++i)
{
for ( int j = 0; j < 3; ++j)
{
for ( int k = 0; k < 2; ++k)
{
cout << "Element at x[" << i << "][" << j
<< "][" << k << "] = " << x[i][j][k]
<< endl;
}
}
}
return 0;
}``````

``````Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11``````