C - Array Multidimensional Arrays

Introduction

A two-dimensional array can be declared as follows:

float numbers[25][50];

This declares the numbers array with 25 sets of 50 floating-point elements.

You could declare another two-dimensional array of floating-point numbers with this statement:

float numbers[3][5];

A three-dimensional array is an extension of a two-dimensional array:

double beans[4] [10][20];                          // 4 fields, each with 10 rows of 20 beans

This declares an array with 800 elements.

Initializing Multidimensional Arrays

You put the initial values for each row between braces, {}, and then enclose all the rows between braces:

int numbers[3][4] = {
                      { 10, 20, 30, 40 },          // Values for first row
                      { 15, 25, 35, 45 },          // Values for second row
                      { 47, 48, 49, 50 }           // Values for third row
                    };

Each set of values that initializes the elements in a row is between braces.

You can initialize the whole array to 0 by supplying just one value:

int numbers[3][4] = {0};

A three-dimensional array, for example, will have three levels of nested braces, with the inner level containing sets of initializing values for a row:

int numbers[2][3][4] = {
                           {                       // First block of 3 rows
                             { 10, 20, 30, 40 },
                             { 15, 25, 35, 45 },
                             { 47, 48, 49, 50 }
                           },
                           {                       // Second block of 3 rows
                             { 10, 20, 30, 40 },
                             { 15, 25, 35, 45 },
                             { 47, 48, 49, 50 }
                          }
                       };

You need a nested loop to process all the elements in a multidimensional array.

The level of nesting will be the number of array dimensions.

Here's how you could sum the elements in the previous numbers array:

int sum = 0;
for(int i = 0 ; i < 2 ; ++i)
{
  for(int j = 0 ; j < 3 ; ++j)
  {
    for(int k = 0 ; k < 4 ; ++k)
    {
      sum += numbers[i][j][k];
    }
  }
}
printf("The sum of the values in the numbers array is %d.", sum);

Here's the previous loop using the sizeof operator to compute the loop control limits:

for(int i = 0 ; i < sizeof(numbers)/sizeof(numbers[0]) ; ++i)
{
  for(int j = 0 ; j < sizeof(numbers[0])/sizeof(numbers[0][0]) ; ++j)
  {
    for(int k = 0 ; k < sizeof(numbers[0][0])/sizeof(numbers[0][0][0])  ; ++k)
    {
      sum += numbers[i][j][k];
    }
  }
}

Related Topics