2. Dynamic Memory Allocation of 2D arrays #
Created Wednesday 25 December 2019
- To create a 2D array in heap,
new int[rows][columns]
, unfortunately, does not work. - We have to create a pointer to a pointer array, where each pointer(element of array) is the start(head) of 10 elements. We can choose column major or row major. Let’s use row-major here.
How to do it:
int** p1 = new int*[10]; //make the array of pointers
for(int i=0; i<10; i++)
p1[i] = new int[10]; //make the array for each pointer.
// p1[10][10] is created.
- Accessing is just like 2D array,
arr[i][j]
= (arr[i])[j] = (*(arr+i))[j] = *(*(arr+i) +j)
. Explanation: [] has an L → R associativity, so first the ‘i’ is used to get the head_pointer of the 'i’th array in the array of pointers, and then this head_pointer is used to get the 'j’th element in the data_type array. - Observations about dynamic arrays using **data_type. It’s not necessary that we make all the ‘rows’ of the same size. We can make them of different sizes too, but that wouldn’t be a 2D array then.
- How to free:
- If we delete arr directly, we’ll lose all the pointers, and the arrays in it. It’ll be a foolish mistake. Only the pointer to arrays will be deallocated, which occupy very little space as compared to the actual array elements.
So, we must first perform deallocation of the array corresponding to each *pointer. Then delete the pointer. Cleaned Successfully. How to do it: for(int i=0; i<10; i++) delete [] p1[i]; // clean each array delete [] p1; // clean the array of pointers Stack vs Heap: https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/ We have a lot of power now. We can do whatever we want. We can make data structures of all kinds using our programming language skills.
- delete NULL is just ignored.