我最近發佈了一個關於此的問題,但這是一個不同的問題。我創建使用動態內存分配的二維數組,使用矩陣後,我們需要釋放被刪除的記憶,我不明白爲什麼我們不能僅低於C++中的二維動態內存分配數組中的空閒分配內存
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 ;
}
使用
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;
}
那麼如果我只是寫'delete []矩陣會發生什麼;'? – Casper 2013-02-12 09:51:41
@ user1986597你將泄漏你分配給矩陣內所有數組的內存。 – 2013-02-12 09:52:14
託尼獅子是正確的,在嚴格的場景中,這是正確的答案,應該在我的腦海中接受。 – odinthenerd 2013-02-12 10:04:28