I'm having difficulty finding an answer on how to specifically perform this operation properly.
I'd like to better understand different ways to delete new memory allocated on the heap, especially in the instance of a two-D array.
For my example: I have an array of size 5 on the stack consisting of int pointers (int *d[5]). I initialize each of these int pointers in a loop to create and point to an int array of size 8 on the heap (d[i] = new int[8]). I have now essentially created a two-D array (d[j][k]).
My question is what is the syntax for deleting only the individual arrays (int[8]) on the heap?
I currently have it as this, but when debugging it appears the arrays are not deallocated after it is performed...
for(int i = 0; i < 5; ++i) delete d[i];
Should it be "delete [] d[i]" or just "delete [] d" or some other variation? Also, is there a way to delete the individual elements of the int[8] arrays? If anyone could concisely explain the syntax and their differences that would be super helpful. Thank you!
If you allocated arrays via d[i] = new int[8]
, then you must delete them via delete[] d[i]
. There's no way to deallocate individual elements of such an array without deallocating the whole thing.