C Language | Arrays | Multidimensional Arrays

This article introduces how to declare multidimensional arrays, using a two-dimensional array with rows and columns like a table as an example.

Multidimensional Data

Information is stored sequentially in physical memory, but it is not always logically one-dimensional. Consider data managed as a table. A table has rows and columns, so its data is arranged in two dimensions.

You could manage such data with an ordinary array, but a two-dimensional array provides more intuitive access. An array whose elements are arrays is called a multidimensional array. Declare one as follows.

Declaring a Multidimensional Array

type variableName[numberOfFirstDimensionElements][numberOfSecondDimensionElements] ...

In a multidimensional array declaration, write one pair of brackets for each dimension and specify the number of elements in each dimension. As with a one-dimensional array, access an element by specifying an index for each dimension. Multidimensional array indices are applied from left to right.

Many kinds of real-world information are multidimensional. Seat management for buses and trains, as well as board games such as Othello and shogi, organize information into categories. Multidimensional arrays are useful for handling such logically divided data.

Code 1

#include <stdio.h>

int main() {
 int iArray[2][2];

 iArray[0][0] = 10;
  iArray[0][1] = 100;
 iArray[1][0] = 1000;
  iArray[1][1] = 10000;

 printf("0,0 = %d : 0,1 = %d\n" , iArray[0][0] , iArray[0][1]);
 printf("1,0 = %d : 1,1 = %d\n" , iArray[1][0] , iArray[1][1]);

 return 0;
}

This program defines a two-dimensional array with two elements in each dimension. It allocates memory for 2 x 2 elements, or four int variables. As Code 1 shows, the iArray array stores four numbers. Logically, it has the following structure.

Table 1 - Contents of the iArray Array

[][0] [][1]
[0][] 10 100
[1][] 1000 10000

Multidimensional arrays are not used as often as one-dimensional arrays. Most information can be represented with one-dimensional arrays. However, fields such as three-dimensional graphics may use four-dimensional arrays. As the number of dimensions increases, memory usage also increases, so use a reasonable number of dimensions.