2014-09-28 90 views
0

我想交換矩陣中的兩行。我的矩陣是一個分配的固體內存塊。 我有一個指向矩陣行的指針數組。第一個指針指向這個大的分配塊。其他指針指向不同的部分或這個塊。用公用指針交換指向已分配內存的指針

如果我交換任何兩行,除了第一個,它沒關係。但我在第一排有問題。 我想這是因爲指向第一行的指針與其他指針不同。但主要區別是什麼?

#include <iostream> 

int** allocateMatrix(int rows, int cols) { 
    // allocating array of pointers (rows) 
    int** matrix = new int*[rows]; 
    // allocating one solid block for the whole matrix 
    matrix[0] = new int[rows*cols]; 

    // setting the pointers for rows 
    for (int i = 1; i < rows; ++i) { 
     matrix[i] = matrix[i-1] + cols; 
    } 

    // fill the matrix with consecutive numbers 
    int k = 1; 
    for (int i = 0; i < rows; ++i) { 
     for (int j = 0; j < cols; ++j) { 
      matrix[i][j] = k; 
      k += 1; 
     } 
    } 

    return matrix; 
} 

void freeMatrix(int** matrix) { 
    delete[] matrix[0]; 
    delete[] matrix; 
} 

int main() { 
    int n = 3; 
    int m = 3; 
    int** matrix = allocateMatrix(n, m); 

    // swap the first and the second line 
    int* tmp = matrix[0]; 
    matrix[0] = matrix[1]; 
    matrix[1] = tmp; 

    // print matrix (it is printing ok) 
    for (int i = 0; i < n; ++i) { 
     for (int j = 0; j < m; ++j) { 
      std::cout << matrix[i][j] << ' '; 
     } 
     std::cout << std::endl; 
    } 

    // problem is here 
    freeMatrix(matrix); 

    return 0; 
} 
+0

創建一個矩陣類,其中包含一個'vector > data'成員,並實現一個交換函數,該函數在數據變量或其某行上調用'std :: swap'。 – 2014-09-28 16:41:17

回答

1

主要區別在於第一個指針由new[]返回。刪除該指針將釋放整個內存塊,但刪除數組中的任何其他指針都會導致未定義的行爲。

您可以將您從new[]單獨獲取的指針存儲起來,並且在您保留在行指針數組中的第一行有一個重複的「弱」指針。

+0

謝謝。我想我沒有想太多。 現在我明白了。 – klimenkov 2014-09-28 19:59:51

0

如果因爲使用matrix[0]刪除內存分配而交換第一行(0)和第二(1)行,您的代碼將無法工作。

您需要以某種方式「保留」原始分配,例如,

int *origalloc; 

... 
origalloc = matrix[0] = new int[rows*cols]; 


... 
delete[] origalloc;  // Instead of malloc[0]; 

傳遞給deletedelete []什麼必須在相同的指針值,你會得到什麼從newnew []回來。其他任何東西都是未定義的行爲。

+0

也謝謝。如果我能給出第二個答案,我也會給你。 – klimenkov 2014-09-28 20:00:45