Suppose we have:
int** myArray = new int*[100];
for(int i = 0; i < 100; i++){
myArray[i] = new int[3];
}
What is the appropriate way to deallocate this array (which method below, if either is a correct way to do so)?
1.
delete[] myArray;
2.
for(int i = 0; i < 100; i++){
for(int j = 0; j < 3; j++){
delete myArray[i][j];
}
}
delete[] myArray;
Intuitively it seems like we should do something like 2. since we want all of the memory we allocated to be deleted, but I'm not sure.
The right method is
You used one loop to create it, you should use one loop to delete it. The order is reversed to the order of allocation:
Moreover:
is for deleting one-dimensional dynamically allocated array - used to delete "rows" and "columns" above.
only resembles how one would delete a 2D array of pointers e.g.:
You can see the "reversed" nature of it.