Kim Lee Kim Lee - 2 months ago 9
C Question

Issue when copying blocks of memory using memcpy

In my following code, I made

buffer
as a 2D array created using
malloc(r * c * sizeof(double*));
. I want to copy the first 12 elements of
buffer
(i.e. the first 4 rows) into the second one
temp
using
memcpy
.

double *buffer = malloc(10 * 3 * sizeof(double*));
double *temp = malloc(4 * 3 * sizeof(double*));

for (int i = 0; i < 4; ++i) {
memcpy(*(temp+ i*3), *(buffer + i*3), 3 * sizeof(double));
}


I get this error:

memcpy(*(temp+ i*3), *(buffer + i*3), 3 * sizeof(double));
^~~~~~~~~~~~~~~~~~~~~~~~~~


Can someone tell me why?

Thank you in advance.

Answer
double *buffer = malloc(10 * 3 * sizeof(double*));

This is wrong, a pointer to double wants space for n doubles (not for n pointers to double)

Change to

double *buffer = malloc(10 * 3 * sizeof(double));

Same for temp

I want to copy the first 12 elements of buffer (i.e. the first 4 rows) into the second one temp using memcpy

memcpy(temp, buffer, sizeof(double) * 12);

Do you want a real 2D array?

In this case you should use

double (*buffer)[cols] = malloc(sizeof(*buffer) * rows); /* VLA (since C99) */

Take a look to defining a 2D array with malloc and modifying it

Comments