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:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy