free the memory

Hello
How can I free the memory allocated by grid ?

1
2
3
4
5
6
7
8
9
 int **grid;
grid = new int*[height];
for(int i = 0; i < height; ++i)
    grid[i] = new int[width];
for(int i=0;i<width;i++)
   for(int j=0;j<height;j++)
   {
      grid[i][j] = 0;
   }


Also, how to free the memory allocated by mapObject?
1
2
   int n =8;
   Map *mapObject = new Map(n,grid);
How do you think it should be done.
Post your attempt.
delete grid;
delete mapObject;
but I am not sure
If you new something, you should delete it.
If you new[] something, you should delete[] it.

See:
https://stackoverflow.com/questions/30720594/deleting-a-dynamically-allocated-2d-array
Last edited on
As ganado said, you need to use delete[] if you used new[].
And you need to use a loop to delete all the rows you "newed" before deleting grid.

1
2
3
4
5
6
for(int i = 0; i < height; ++i)
    delete[] grid[i];
delete[] grid;

// And you're right about mapObject
delete mapObject;

Thanks a lot. It works.
Topic archived. No new replies allowed.