我最近发布了关于这个问题,但是这是一个不同的问题。 我创建使用动态内存分配的二维数组,使用矩阵后,我们需要释放被删除的记忆,我不明白为什么我们不能只是使用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()
我创建一个二维数组,并使用其他分配值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;
}