# What is a 2D array in C.

### 14.11 Two-dimensional dynamic arrays

In Section 12.9 you read that the area of ​​application of pointers to pointers is, among other things, the dynamic creation of matrices. I don't want to torment you now and take the matrix calculation as a topic, I will just make simple memory reservations with rows and columns:

int matrix [row] [column];

So to reserve memory for a two-dimensional array with any number of rows and columns, you first need space for the row. And for each of these lines, additional space is required for the column. When freeing the memory, this must be done in reverse order.

Here is the full listing:

/ * 2D_dyn_array.c * / #include #include #define BUF 255 int main (void) {int i, j, line, column; / * Matrix is ​​pointer to int pointer. * / int ** matrix; printf ("How many lines:"); scanf ("% d", & line); printf ("How many columns:"); scanf ("% d", & column); / * Reserve memory for the int pointer (= line) * / matrix = malloc (line * sizeof (int *)); if (NULL == matrix) {printf ("No more virtual RAM available ...!"); return EXIT_FAILURE; } / * now reserve memory for the individual columns * of the i-th row * / for (i = 0; i

Admittedly, the listing has it all. For some it might seem a bit opaque how ** matrix becomes matrix [line] [column]. The best thing to do is to just take a look at what happened when the following memory reservation was made:

matrix = malloc (line * sizeof (int));

As an example, we want to create a 4 × 3 matrix, i.e. four rows and three columns.

Figure 14.9 Reservation of memory for the row (first dimension)

Now that you've reserved memory for each row, the next step is to reserve memory for each column.

for (i = 0; i

The final image from Figure 14.10 then results in the memory.

Figure 14.10 After reserving memory for the column

You will probably remember the demonstration of equivalent access to a memory object using a pointer and an array in Chapter 12, "Pointers". There are also some equivalent cases for pointers to pointers and the two-dimensional arrays. You can find them listed in Table 14.2.

 access to Possibility Number 1 Possibility 2 Option 3 1st row, 1st column i. Row, 1st column 1st line, i. column i. Row, j. column