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.