我最近发布了一个关于此的问题,但这是一个不同的问题。我使用动态内存分配创建了一个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;
}
答案 0 :(得分:7)
您必须浏览矩阵并删除每个数组。在这样做结束时,您可以删除矩阵本身
// free dynamically allocated memory
for( int i = 0 ; i < *row ; i++ )
{
delete[] matrix[i]; // delete array within matrix
}
// delete actual matrix
delete[] matrix;
答案 1 :(得分:3)
如果你正在使用动态数组,我强烈建议使用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惯例的大师们的说法,它只应该用于性能优化和编写库代码时。许多书籍和教师仍然以这种方式教学,但另一方面,大多数书籍都是垃圾。以下是其中的宝石:The Definitive C++ Book Guide and List
答案 2 :(得分:0)
因为类型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这样的标准容器。