Bidimensional Arrays Dynamic Memory

Hello,

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:

Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main() {
	const int rows = 4;
	const int cols = 4;

	// declaration
	int ** a;

	// allocation
	a = new int*[rows];
	for(int i = 0; i < rows; i++)
		a[i] = new int[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;
}


Thanks,
LoOpz
You delete it the exact same way you allocated it.

Since you allocated each row with new in a loop, you must delete each row with delete in a loop:

1
2
3
for(int i = 0; i < rows; ++i)
  delete[] a[i];
delete[] a;


Also, obligatory link: http://cplusplus.com/forum/articles/17108/
Last edited on
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
inline int index(int x, int y) {
return x+y*WIDTH;
};

int *array = new int[WIDTH*HEIGHT];
array[index(5,3)] = ...
delete [] array;

Last edited on
Thanks alot!
Topic archived. No new replies allowed.