2013-02-12 81 views
1

我最近發佈了一個關於此的問題,但這是一個不同的問題。我創建使用動態內存分配的二維數組,使用矩陣後,我們需要釋放被刪除的記憶,我不明白爲什麼我們不能僅低於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; 
    } 

回答

7

你必須遍歷你的矩陣並刪除每個數組。在這樣做的結尾你可以刪除矩陣本身

// free dynamically allocated memory 
for(int i = 0 ; i < *row ; i++) 
{ 
    delete[] matrix[i]; // delete array within matrix 
} 
// delete actual matrix 
delete[] matrix; 
+0

那麼如果我只是寫'delete []矩陣會發生什麼;'? – Casper 2013-02-12 09:51:41

+0

@ user1986597你將泄漏你分配給矩陣內所有數組的內存。 – 2013-02-12 09:52:14

+0

託尼獅子是正確的,在嚴格的場景中,這是正確的答案,應該在我的腦海中接受。 – odinthenerd 2013-02-12 10:04:28

2

如果你使用動態數組,無論如何我會強烈建議使用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 

使用新的和刪除不是真正的現代風格,有很好的理由。根據C++和Beyond慣例中的指導,它應該僅用於性能優化和編寫庫代碼的情況。許多書籍和老師仍然這樣教,但另一方面,大多數書籍都是垃圾。這裏是其中的寶石:The Definitive C++ Book Guide and List

+0

感謝您的輸入,但我還沒有學到通用但:) – Casper 2013-02-12 09:56:16

+0

我要添加示例代碼 – odinthenerd 2013-02-12 09:57:11

+0

謝謝,它看起來很整潔,保存它:) – Casper 2013-02-12 10:05:44

0

因爲類型int *沒有desctructor,至少它沒有你想要的析構函數。你可以做這樣的事情

std::vector<int*> matrix(rows); 
std::vector<int> allData(rows * cols); 
for(int i = 0; i < rows; i++) 
{ 
matrix[i] = &allData[i * cols]; 
} 

,或者使用類似的boost ::數字:: uBLAS庫::矩陣標準集裝箱避免所有的內存分配/釋放的東西。