Dynamically Allocate Memory for 2D Array

In this post, we 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 pointer. Even though the memory is linearly allocated, we can use pointer arithmetic to index 2D array.

C

Download   Run Code

2. Using Array of Pointers

We can dynamically create 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

C

Download   Run Code

3. Using Double Pointer

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

C

Download   Run Code

 
Dynamically Allocate Memory for 3D Array
 

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of