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