Skip over navigation

2D Arrays

Declaring and Accessing Two-Dimensional Arrays

Terms List

Problems and Solutions 1

The first step in understanding arrays of more than one dimension is learning how to create the desired structure. Declaring a two-dimensional array is very similar to a one- dimensional array and differs only in that you need to specify both dimensions of the array as opposed to just one. So to specify an array the models the 8x8 chess board, one might do the following:


#define	NUM_ROWS	8
#define NUM_COLS	8
typedef enum {
	EMPTY,
	KING,
	QUEEN,
	ROOK,
	BISHOP,
	KNIGHT,
	PAWN
} piece_t;

piece_t	board[NUM_ROWS][NUM_COLS];

It is generally good style to sharp-define the bounds of a static array so that you can refer back to them in your code. This prevents having constant values sprinkled throughout your code that do not have any intuitive meaning. In addition, sharp-defines make a program easier to maintain. A sharp-defined value can be modified by making one change while many changes would have to be made if literal numbers were used.

Setting the values in a two-dimensional array is analogous to setting the values in a one-dimensional array. You can simply specify one specific cell in the array and use it as you would any other variable of that particular type. For example:


board [0][0] = ROOK;

As another example you could check if the location specified by the variables row and col by doing the following:


if (board[row][col] == EMPTY) {
	/* your code here */
}

As you can see, once you have mastered working with one-dimensional arrays, the transition to using two-dimensional arrays is rather simple.

In fact, the transition to any number of dimensions is relatively easy. Basically the only difference between accessing and assigning to and from a two-dimensional array and a multi-dimensional array is the number of indices that you need to specify. For an n-dimensional array, n indices. must be used. A particular cell in a five-dimensional array may be accessed as follows:


arr5[dim1][dim2][dim3][dim4][dim5]

As you can see, mastery of 2-dimensional arrays is easily extended to n-dimensional arrays. The key is that an n-dimensional array requires n indices.

Follow Us