Hirosam Hirosam - 3 months ago 13
C Question

Copying a pointer of a pointer (matrix) values in C

The problem is the following:
I created a dynamic matrix, using pointer to pointer

matrix1


I want to create a copy of this matrix into another,
matrix2


I want to do that so I can mess with
matrix2
without messing with
matrix1

So I tried to do the following:

int main()
{
int **matrix1, **matrix2, size1 = 10, size2 = 2;
matrix1 = create_matrix(size1, size2);

//I want to copy the value of matrix1 into matrixq2 and NOT the index
**matrix2 = **matrix1
}


However the program breaks and show the following: Error

I understand that by the way it look, it would be easier to use the function
create_matrix
two times, for
matrix1
and another for
matrix2
. But in the way that my original program is that would be too much work, since I do a lot of stuff to have the matrix done.
Oh, and by the way, I want to avoid using C++, is there is a way to do it without using it? It would be better for me.

Answer

Going out on a limb about your incomplete code, create_matrix returns an array of row pointers that point within a buffer of ints of the appropriate size.

This means that matrix1 points to the array of row pointers, *matrix1 is a pointer to the array holding the actual data (address of the first element), and **matrix1 is the value of first element. matrix1 and *matrix1 are both dynamically allocated arrays.

matrix2 is an uninitialized (trash) pointer in the code you have displayed. It has neither the row pointer nor data buffers allocated.

To achieve your desired result, you need to first allocate the elements of matrix2, then copy just the data portion of matrix1 over:

matrix2 = create_matrix(size1, size2);
memcpy(*matrix2, *matrix1, size1 * size2 * sizeof(int));

The copy operation does not touch the contents of the row pointers, just the data buffer.