-3

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.

6
  • 4
    Surely this is not the entirety of the compiler's diagnostic? Commented Sep 6, 2016 at 16:53
  • There is no 2D array, but a 1D array. Any reason you don't use a 2D array, but do the indexing maths by hand? Commented Sep 6, 2016 at 16:55
  • And what is the error message? See How to Ask and provide a minimal reproducible example. Commented Sep 6, 2016 at 16:55
  • Can you tell us what the error says? Commented Sep 6, 2016 at 16:56
  • This is the error: ` error: passing 'double' to parameter of incompatible type 'const void * ` Commented Sep 6, 2016 at 17:04

1 Answer 1

2
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

Use:

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

I get this error:

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

Can someone tell me why?

memcpy wants a pointer (an address) but you are dereferencing the pointer (thus passing a value like 3.14 instead of an address)

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

Sign up to request clarification or add additional context in comments.

7 Comments

Or use a 2D array ...
Thank you very much
@Olaf, you are right, but it seems to me that OP wants a flat 2D array (due to the dimensions passed in malloc)
@AlterMann: You have to pass the dimensions anyway to malloc. I don't think OP wants a 1D array. He just might not know there is a better alternative. (anyway, a better way to get the size of an element is sizeof(* buffer) instead of repeating the type explicitly. And yes, that works for pointers to VLA, too.
Yes, the alternative you mentioned is just great. However, it says: compound array initializer is expected. Do you know what does this mean
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.