2014-09-28 55 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