120 Intermediate C Programming
arr2d [3][1] = 6;5
// assign 6 to the second column of the fourth row6
In this example, the first dimension has eight rows and the indexes are between zero
and seven (inclusively). The second dimension has three columns; the indexes are between
zero and two. A two-dimensional array is like a matrix.
It is a little more complicated creating a two-dimensional array whose size is known only
at run time by calling malloc. We first create a one-dimensional array of integer pointers
(int *) and then each pointer is used to create an integer array. Fig. 8.1 illustrates this
concept. The first step creates an array of integer pointers. In the second step, each pointer
stores the address of the first element in a one-dimensional integer array. The addresses of
&arr2d[0] and &arr2d[1] are adjacent. However, the values of arr2d[0] (corresponding
to &arr2d[0][0]) and arr2d[1] (corresponding to &arr2d[1][0]) are likely far apart.
FIGURE 8.1: A two-dimensional array has an array of pointers as the first dimension.
Each element points to an array.
An array’s name stores the address of the first element. Therefore, the type of a one-
dimensional array of integers is an integer pointer. If we want to create an array using
malloc, we need to use int *.
int arr [6]; /* an array of fixed size , 6 elemen t s */1
int * arr2 ; /* an integer pointer */2
arr2 = malloc (9 * s i z e o f ( in t ) ); /* 9 e lements */3
arr2 [4] = 19; /* arr2 [4] is an integer */4
free ( arr2 ) ;5
Imagine a new type called one d array. A two-dimensional array would be an array of
one d array. To create this two-dimensional array, malloc is used:
one_d_ array * arr2d ;1
arr2d = malloc ( numrow * s i z e o f ( one _d_array ) ) ;2
The one-dimensional array is itself a pointer to integer; thus, one d array should be
replaced by int *. Consequently, the type of arr2d is int * *. That means that the arr2d
is pointing to int *, and indeed, the first element of arr2d has type int *.