Skip over navigation

2D Arrays

Problems and Solutions 1

Declaring and Accessing Two-Dimensional Arrays

Looping Constructs for Two-Dimensional Arrays

Problem : Define a data type that will hold a tic-tac-toe board.


typedef enum {
	EMPTY,
	X,
	O
} ttt_piece_t;
typedef ttt_piece_t[3][3] 	ttt_board_t;
If you include these type definitions at the beginning of a program every time that you declare a variable of type ttt_board_t it will allocate space for a 3 by 3 array of ttt_piece_t.

Problem : If you had two pieces of information to store for each student in a class, the average and the rank, what dimension array should you use?

In this case it makes sense to use a 2-dimensional array. For student n, class[n][0] could hold the average and class[n][1] could hold the rank. Another solution is to use a struct to combine the two pieces of information and then make an array of structs.

Follow Us