当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Swap a pointer to the allocated memory with a common pointer

问题描述:

I want to swap two lines in a matrix. My matrix is an allocated solid block of memory.

I have an array of pointers that point to the rows of the matrix. The first pointer points to this big allocated block. And other pointers point to different parts or this block.

If I swap any two rows, except the first, it's OK. But I have problems with the first row.

I guess that's because the pointer to the first row is different from other. But what is the main difference?

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

}

网友答案:

The main difference is that the first pointer was returned by new[]. Deleting that pointer will deallocate the entire memory block, but deleting any other pointer in the array will have undefined behaviour.

You could store the pointer which you get from new[] separately, and have a duplicate "weak" pointer to the first row that you keep in the array of row pointers.

网友答案:

Your code won't work if you swap first (0) and second (1) rows because you are using matrix[0] to delete the memory allocation.

You need to somehow "keep" the original allocation, e.g.

 int *origalloc; 

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


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

What you pass to delete or delete [] must the the same pointer-value as what you get back from the new or new []. Anything else is undefined behaviour.

分享给朋友:
您可能感兴趣的文章:
随机阅读: