free allocated memory in 2D dynamic memory allocation array in C++

末鹿安然 提交于 2019-11-29 08:51:27

You have to go through your matrix and delete each array. At the end of doing that you can delete the matrix itself

// free dynamically allocated memory
for( int i = 0 ; i < *row ; i++ )
{
    delete[] matrix[i]; // delete array within matrix
}
// delete actual matrix
delete[] matrix;
odinthenerd

If you are using dynamic arrays anyway I would highly suggest using std::vector. The performance penalty is next to nothing and considering you can use std algorithms more gracefully with vectors your code may very well end up more performant.

unsigned int cols=40, rows=35;
std::vector<int> temp(cols,0); //this is only created so that we can initialize a 
                               //row at a time, the first parameter is the amount of 
                               //elements to initialize with and the second is the value
                               //to initialize with
std::vector<std::vector<int>> matrix(rows,temp); //creates a vector with 35 vectors each
                                                 //initialized with the values in temp

matrix[2][3] = 4;              //use just like a normal array
matrix.resize(88,temp);         //you can add rows later too
matrix.push_back(temp);         //or like this

//probably the most important, you don't need to delete because you never needed to 
//use new in the first place

using new and delete is not really modern style, for good reason. According to the gurus at the C++ and Beyond convention it should be used only in the case of performance optimization and when writing library code. Many books and teachers still teach this way, but on the other hand most books are junk. Here are the gems among them: The Definitive C++ Book Guide and List

Because type int* has no desctructor, at least it has no destructor that you want. You could avoid all memory allocating / deallocation stuff by doing something like this

std::vector<int*> matrix(rows);
std::vector<int> allData(rows * cols);
for(int i = 0; i < rows; i++)
{
matrix[i] = &allData[i * cols];
}

or by using a standard container like boost::numeric::ublas::matrix.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!