The C language allows arrays of any type including arrays of arrays. These are sometimes known as multidimensional arrays.
For Example:
double x[10][20];
is a declaration for an array, x, with 10 elements, each of which contains an array with 20 elements.
Declarations of arrays | Notes |
int a[100]; | a one-dimensional array |
int b[4][8]; | a two-dimensional array |
int c[5][3][2]; | a three-dimensional array |
In the preceding example, each element of the array is accessed using the expression
x[ i ][ j ]
The Array indices can not be folded into one subscript in c language,
x[ i , j ]
2D or Two Dimensional Array
Visualizes a 2D array as a matrix that has both rows and columns
For example, an array declared as
int a[3][4];
the array elements are arranged as follows:
Column0 | Column1 | Column2 | Column3 | |
row0 | a [0][0] | a[0][1] | a[0][2] | a[0][3] |
row1 | a[1][0] | a[1][1] | a[1][2] | a[1][3] |
row2 | a[2][0] | a[2][1] | a[2][2] | a[2][3] |
The general form of a 2D array declaration is:
e_type a_name[r_size][c_size];
where
- e_type is the type of the array elements
- a_name is the name of the array
- r_size is the number of rows in the array
- c_size is the number of columns in the array
The number of pairs of brackets, [ ], denotes the dimensionality.
2D Array Initialization
- An array initializer is a sequence of initializing values written as a brace-enclosed, comma-separated list.
- Each row is contained in braces.
- Each element in a two-dimensional array is referenced using an identifier followed by two subscripts [ ] [ ]
- The subscript values for both rows and columns begin with 0, and each subscript has its own set of brackets.
int j[2][2] = {{1,2},{3,4}};
declares j to be a 2´2, 4-element, integer array whose elements have the initial values
j[0][0]=1 j[0][1]=2
j[1][0]=3 j[1][1]=4
The following three array initializations are equivalent.
int a[2][3] = {1, 2, 3, 4, 5, 6};
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int a[ ][3] = {{1, 2, 3}, {4, 5, 6}};
Higher Dimensional Arrays
C allows arrays to be defined with more than two subscripts. A three-dimensional (3D) array is really a series of two-dimensional arrays. For example, to declare a 3D array volume:
int volume[10][10][10];
Declares a 10´10´10 array containing 1000 elements: essentially 10 2D arrays, each containing 100 elements.
3D arrays are often used to specify 3D information.
4D arrays are often used to specify time-series data.