I know how to dynamically allocate bidimensional or multidimensional arrays. But the problem is when I free the memory space. I know I have to delete the memory row by row, but I do not exactly how to do it.
I know there is a previous post I saw with the same topic, but it's just that I don't know how to properly delete the memory allocated:
int main() {
constint rows = 4;
constint cols = 4;
// declaration
int ** a;
// allocation
a = newint*[rows];
for(int i = 0; i < rows; i++)
a[i] = newint[cols];
// initialization
for(int j = 0; j < rows; j++)
for(int i = 0; i < rows; i++)
a[i][j] = 0;
//To free memory space (Here is the problem):
delete[] a[rows]; //I thought I have to do this first, but I'm not sure.
delete[] a;
return 0;
}
You need to loop over all rows to delete each column. Just like you did with new to create them.
This is a great way of storing the data if you want to do row transpositions, but requires two dereference for each access which is not good. For general use you would be much better to index a one dimensional array.
1 2 3 4 5 6 7
inlineint index(int x, int y) {
return x+y*WIDTH;
};
int *array = newint[WIDTH*HEIGHT];
array[index(5,3)] = ...
delete [] array;