How to Declare an Initialized Multidimensional Array in C Programming

By Dan Gookin

In C programming, the dark secret of multidimensional arrays is that they don’t really exist. Internally, the compiler still sees things as single dimensions — just a long array full of elements. The double (or triple) bracket notation is used to calculate the proper offset in the array at compile time. That’s okay because the compiler does the work.

You can see how multidimensional arrays translate into regular old boring arrays when you declare them already initialized. For example:

int grid[3][4] = {
 5, 4, 4, 5,
 4, 4, 5, 4,
 4, 5, 4, 5
 };

The grid array consists of three rows of four items each. As just shown, it’s declared as a grid and it looks like a grid. Such a declaration works, as long as the last element doesn’t have a comma after it. In fact, you can write the whole thing like this:

int grid[3][4] = { 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5 };

This statement still defines a multidimensional array, but you can see how it’s really just a single-dimension array with dual indexes. In fact, the compiler is smart enough to figure out the dimensions even when you give only one of them, as in this example:

int grid[][4] = { 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5 };

In the preceding line, the compiler sees the 12 elements in an array grid, so it automatically knows that it’s a 3-by-4 matrix based on the 4 in the brackets. Or you can do this:

int grid[][6] = { 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5 };

In this example, the compiler would figure that you have two rows of six elements. But the following example is just wrong:

int grid[][] = { 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5 };

The compiler isn’t going to get cute. In the preceding line, it sees an improperly declared single-dimension array. The extra square brackets aren’t needed.

Exercise 1: Rewrite the code from Tic-Tac-Toe so that the tic-tac-toe game board is initialized when the array is declared — including putting the X in the proper spot.

TIC-TAC-TOE

#include <stdio.h>
int main()
{
  char tictactoe[3][3];
  int x,y;
/* initialize matrix */
  for(x=0;x<3;x++)
    for(y=0;y<3;y++)
      tictactoe[x][y]='.';
  tictactoe[1][1] = 'X';
/* display game board */
  puts("Ready to play Tic-Tac-Toe?");
  for(x=0;x<3;x++)
  {
    for(y=0;y<3;y++)
      printf("%ct",tictactoe[x][y]);
    putchar('n');
  }
  return(0);
}