This post will discuss various methods to dynamically allocate memory for 2D array in C using Single Pointer, Array of Pointers, and Double Pointer.

1. Using Single Pointer

In this approach, we simply allocate memory of size M × N dynamically and assign it to the pointer. Even though the memory is linearly allocated, we can use pointer arithmetic to index the 2D array.

Download  Run Code

2. Using Array of Pointers

We can dynamically create an array of pointers of size M and then dynamically allocate memory of size N for each row, as shown below:

Dynamically allocate memory for 2D Array

Download  Run Code

3. Using Double Pointer

We start by creating an array of pointers of size M as seen in the 2nd method. Then dynamically allocate memory of size M × N and let *A point to it. Finally, position allocated memory across M pointers.

Download  Run Code

That’s all about dynamically allocating memory for a 2D array in C.

 
Also See:

Dynamically allocate memory for a 3D array in C