Dynamic Memory Allocation in C++ for 2D and 3D array

In this post, we will discuss dynamic memory allocation in C++ for multi-dimensional arrays.

 

  1. Single Dimensional Array
     
  2. 2-Dimensional Array
     
  3. 3-Dimensional Array

 
 

Single Dimensional Array

 

Download   Run Code

 

2-Dimensional Array

 

1. Using Single Pointer

In this approach, we simply allocate one large block of memory of size M*N dynamically and assign it to pointer. Then we can use pointer arithmetic to index 2D array.

 

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:

Dynamic memory allocation in C++ for 2D array

 

Download   Run Code

 

3-Dimensional Array

 

1. Using Single Pointer

As seen for 2D array, we allocate memory of size X*Y*Z dynamically and assign it to a pointer. Then we use pointer arithmetic to index 3D array.

 

Download   Run Code

 

2. Using Triple Pointer

 

Download   Run Code

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz