Allocating 2-D Arrays on Heap
Learn to allocate a two-dimensional array on the heap as an array of pointers to arrays.
Introduction
We’ve seen that allocating one-dimensional arrays is pretty straightforward. To allocate one array of 15 doubles, we can write the following:
double arr = malloc(15 * sizeof(double));
Then we can use this array just like we use any other array:
arr[0] = 5.0; //to write to the array
double x = arr[1]; //to read from the array
The question is, how can we dynamically allocate arrays with higher dimensions? We’ll present a strategy called “arrays of pointers to arrays” for the two-dimensional case. This strategy can extend to three-dimensional arrays and beyond.
Matrix structure
To understand this technique, let’s inspect how a 3x4 matrix looks:
As per the image above, we can view the matrix as multiple arrays stacked on top of each other, and each array is one row. Therefore, a matrix or two-dimensional array is an array of arrays.
To dynamically allocate a matrix with n
lines and m
columns, imagine dynamically allocating n
individual one-dimensional arrays, where each array will serve as a row. We know how to allocate one-dimensional arrays, so this is doable.
For example, if we assume a 3x4 matrix that stores integers, we can do:
malloc(4 * sizeof(int)) //allocate first row array
malloc(4 * sizeof(int)) //allocate second row array
malloc(4 * sizeof(int) //allocate third row array
malloc(4 *
...