+ 2

Ho to delete pointers and free memory properly?

I want to write a server in c++. How should I destruct objects properly , delete 2 dimensional dynamic arrays of objects and free memory?

22nd Jan 2018, 2:47 AM
code learner
code learner - avatar
3 odpowiedzi
+ 5
The rule goes "one delete for every new". If you want to delete an entire array of objects, you can use delete[]. If your array is 2d, you'll have to loop over it, delete[] every row, the delete[] the whole thing. for(int i = 0; i < len; i++) delete[] my_2d_array[i]; delete[] my_2d_array;
22nd Jan 2018, 2:54 AM
Schindlabua
Schindlabua - avatar
+ 4
Also, my recommendation: You probably don't need a 2d array at all! You can make a single array of size width*height, and store the board row by row in there. To get the Cell at position (x,y), you can use my_1d_array[y * width + x]; Not only is it nicer to work with (in my opinion anyway), it's also good for performance since all the Cells will be next to each other in memory. If you have an array of pointers that's likely not the case!
22nd Jan 2018, 3:00 AM
Schindlabua
Schindlabua - avatar
+ 3
I am writing connect 4 game . I have two classes Board and Cell both have parameterized constructor. Inside class Board there is 2d dynamic array of Cell objects like -> Cell ***cells; so user can specify board dimensions and accordingly 2d array of Cell objects is created. I want to destroy this array inside destructor
22nd Jan 2018, 2:55 AM
code learner
code learner - avatar