6.5. Multidimensional Arrays

The array we used in the last example was a one dimensional array. Arrays can have more than one dimension, these arrays-of-arrays are called multidimensional arrays. They are very similar to standard arrays with the exception that they have multiple sets of square brackets after the array identifier. A two dimensional array can be though of as a grid of rows and columns.

Example 6-3. number_square.c

#include <stdio.h>

const int num_rows = 7;
const int num_columns = 5;

int
main()
{
  int box[num_rows][num_columns];
  int row, column;

  for(row = 0; row < num_rows; row++)
    for(column = 0; column < num_columns; column++)
      box[row][column] = column + (row * num_columns);

  for(row = 0; row < num_rows; row++)
    {
      for(column = 0; column < num_columns; column++)
        {
          printf("%4d", box[row][column]);
        }
      printf("\n");
    }
  return 0;
}
      

If you compile and run this example you'll get a box of numbers like this:

   0   1   2   3   4
   5   6   7   8   9
  10  11  12  13  14
  15  16  17  18  19
  20  21  22  23  24
  25  26  27  28  29
  30  31  32  33  34
     

The above array has two dimensions and can be called a doubly subscripted array. GCC allows arrays of up to 29 dimensions although actually using an array of more than three dimensions is very rare.