使用公用指针交换指向已分配内存的指针

Swap a pointer to the allocated memory with a common pointer

本文关键字:指针 内存 分配 交换      更新时间:2023-10-16

我想交换矩阵中的两行。我的矩阵是一个分配的实心内存块。我有一个指向矩阵行的指针数组。第一个指针指向这个已分配的大块。其他指针指向不同的部分或这个块。

如果我换掉除第一行以外的任何两行,都没关系。但我对第一行有问题。我想这是因为指向第一行的指针与其他指针不同。但主要区别是什么?

#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;
}

主要区别在于第一个指针是由new[]返回的。删除该指针将解除分配整个内存块,但删除数组中的任何其他指针将具有未定义的行为。

您可以单独存储从new[]获得的指针,并在行指针数组中保留一个指向第一行的重复"弱"指针。

如果交换第一(0)行和第二(1)行,您的代码将无法工作,因为您正在使用matrix[0]删除内存分配。

您需要以某种方式"保留"原始分配,例如

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

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

传递给deletedelete []的指针值必须与从newnew []返回的指针值相同。任何其他行为都是未定义的行为。