This is some code I wrote just to understand working with pointers. Here I want to allocate and display a 2-dimensional Pointerarray
int main()
{
constexpr int size = 10;
int** _2darray = new int* [size];
for ( int i = 0; i < size; i++ )
{
*(_2darray + i) = new int[i];
for ( int j = 0; j <= i; j++ )
{
*(*(_2darray + i) + j) = j;
}
}
for ( int i = 0; i < size; i++ )
{
for ( int j = 0; j <= i; j++ )
{
std::cout << _2darray[i][j] << " ";
}
std::cout << std::endl;
}
}
This will result in printing this:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
But if I want to prevent a memory leak now, I would want to do this:
for ( int i = 0; i < size; i++ )
{
delete[] _2darray[i];
}
delete[] _2darray;
Unfortunately this will give me an exception that the heap was corrupted
I guess that it crashes because it doesen't know the exact size of the subarrays, but I also heard that delete always keeps track of how much bytes are being allocated for a array.
Thank you for any short answer.

<=in it. Check the range ofjthat results fromfor ( int j = 0; j <= i; j++ )to make certain it's what you expect.*(_2darray + i) = new int[i];given that the for loop is initialized with i=0. You are allocating an array with zero items in it and then writing to itint** _2darray = new int* [size];allocates forsizepointers.*(_2darray + i) = new int[i];allocates fori intand assigns the starting address for that block to your pointers in turn. When you want to free the memory, you must first loop over your pointers freeing the allocated blocks ofintbefore freeing the block of pointers.for (int i = 0; i < size; i++) delete[] _2darray[i];then free your block of pointers,delete[] _2darray;. (note: there are no "arrays" involved, you have allocated blocks of memory) Also note:_2darray[i]and_2darray[i][j]are readable.