我最近发布了一个关于这个的问题,但这是一个不同的问题。我使用动态内存分配创建了一个2D阵列,在使用矩阵后,我们需要通过删除它来释放内存,我不明白为什么我们不能只使用delete [] matrix
来删除它,而不是下面代码中的方法
int **matrix;
// dynamically allocate an array
matrix = new int *[row];
for (int count = 0; count < row; count++)
matrix[count] = new int[col];
// free dynamically allocated memory
for( int i = 0 ; i < *row ; i++ )
{
delete [] matrix[i] ;
delete [] matrix ;
}
因为问题是因为在main()
中,我创建了一个2D数组,并使用其他int **
函数分配值,我不知道如何删除分配的内存,循环将导致运行时错误
int main()
{
int **matrixA = 0, **matrixB = 0, **matrixResult = 0; // dynamically allocate an array
int rowA, colA, rowB, colB; // to hold the sizes of the matrices
// get values for input method
int inputMethod = userChoiceOfInput();
if (inputMethod == 1) // select input by keyboard
{
cout << "Matrix A inputting...n";
matrixA = getMatricesByKeyboard(&rowA, &colA);
cout << "Matrix B inputting...n";
matrixB = getMatricesByKeyboard(&rowB, &colB);
}
else if (inputMethod == 2) // select input by files
{
matrixA = getMatricesByFileInput("F:\matrixA.txt", &rowA, &colA);
matrixB = getMatricesByFileInput("F:\matrixB.txt", &rowB, &colB);
}
//addition(matrixA, &rowA, &colA, matrixB, &rowB, &colB);
cout << matrixA[1][0];
////////////////////////run time error///////////////////////
// free allocated memory of matrix A
for( int i = 0 ; i < rowA ; i++ )
{
delete [] matrixA[i] ;
delete [] matrixA ;
}
// free allocated memory of matrix B
for( int i = 0 ; i < rowB ; i++ )
{
delete [] matrixB[i] ;
delete [] matrixB ;
}
////////////////////////run time error///////////////////////
// free allocated memory of matrix A
delete [] matrixA ; // i dont know what would these delete
delete [] matrixB ;
return 0;
}
您必须遍历矩阵并删除每个数组。完成后,您可以删除矩阵本身
// free dynamically allocated memory
for( int i = 0 ; i < *row ; i++ )
{
delete[] matrix[i]; // delete array within matrix
}
// delete actual matrix
delete[] matrix;
如果您使用的是动态数组,我强烈建议您使用std::vector。性能损失几乎没有,考虑到你可以更优雅地使用std算法和向量,你的代码最终可能会更具性能。
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
使用new和delete并不是真正的现代风格,这是有充分理由的。根据C++和Beyond约定的大师们的说法,它应该只在性能优化和编写库代码的情况下使用。许多书和老师仍然以这种方式教学,但另一方面,大多数书都是垃圾书。以下是其中的精华:最终C++图书指南和列表
因为类型int*没有解构函数,所以至少它没有您想要的析构函数。你可以通过做这样的来避免所有内存分配/释放的事情
std::vector<int*> matrix(rows);
std::vector<int> allData(rows * cols);
for(int i = 0; i < rows; i++)
{
matrix[i] = &allData[i * cols];
}
或者使用标准容器,如boost::numeric::ublas::matrix。