C Multidimensional arrays

C Arrays

The C language supports multidimensional arrays. The general form of a multidimensional array declaration is as follows:

type name[size1][size2]...[sizeN];

For example, the following declaration creates a three-dimensional 5 . 10 . 4 integer array:

int threedim[5][10][4];

Two-dimensional array

The simplest form of a multidimensional array is a two-dimensional array. In essence, a two-dimensional array is a list of one-dimensional arrays. To declare a two-dimensional integer array with x rows and y columns, the form is as follows:

type arrayName [ x ][ y ];

where,typetype can be any valid C data type,arrayNamearrayName is a valid C identifier. A two-dimensional array can be considered a table with x rows and y columns. The following is a two-dimensional array containing 3 rows and 4 columns:

int x[3][4];
C 中的二维数组

Therefore, each element in the array is identified by an element name of the form a[ i , j ], where a is the array name, and i and j are the subscripts that uniquely identify each element in a.

Initialize two-dimensional array

Multidimensional arrays can be initialized by specifying values for each row inside the braces. The following is an array with 3 rows and 4 columns.

int a[3][4] = {  
 {0, 1, 2, 3} ,   /*  初始化索引号为 0 的行 */
 {4, 5, 6, 7} ,   /*  初始化索引号为 1 的行 */
 {8, 9, 10, 11}   /*  初始化索引号为 2 的行 */
};

The inner nested braces are optional; the following initialization is equivalent to the one above:

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

Accessing 2D array elements

Elements in a two-dimensional array are accessed by using subscripts (i.e., the array's row index and column index). For example:

int val = a[2][3];

The above statement will get the element in the 3rd row and 4th column of the array. You can verify this with the diagram above. Let's take a look at the following program; we will use nested loops to process a two-dimensional array:

Example

#include <stdio.h> int main () { /*An array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j; /*Output the value of each element in the array*/ for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf("a[%d][%d] = %d\n", i,j, a[i][j] ); } } return 0; }

When the above code is compiled and executed, it produces the following results:

a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8

As mentioned above, you can create arrays of any dimension; however, in general, the arrays we create are one-dimensional and two-dimensional arrays.

C Arrays

other extensions