Nark Nark - 1 month ago 19
C Question

C - Memcpy two int's to a single Void pointer

I am trying to copy two ints into a void pointer, and be able to access them, so far no luck.

void *buffer;
buffer = malloc (sizeof(int) + sizeof(int))
memcpy (&buffer, &int1, sizeof(int));
memcpy (&buffer + sizeof(int), &int2, sizeof(int));
printf ("%d", *(int*)buffer);


When printing, all I get is the value in the first 4 bytes. Any help would be appreciated, thanks.

Answer

You are copying to pointer of the pointer.

Change these two lines:

memcpy (&buffer, &int1, sizeof(int));
memcpy (&buffer + sizeof(int), &int2, sizeof(int));

To be this:

memcpy (buffer, &int1, sizeof(int));
memcpy (buffer + sizeof(int), &int2, sizeof(int));

Better form:

void* buffer = malloc(sizeof(int) * 2);
int* intbuffer = (int*)buffer;

memcpy(intbuffer, &int1, sizeof(int));
memcpy(intbuffer+1, &int2, sizeof(int));

You can even avoid the memcpy altogether:

void* buffer = malloc(sizeof(int) * 2);
int* intbuffer = (int*)buffer;

intbuffer[0] = int1;
intbuffer[1] = int2;

The corresponding printf("%d", *(int*)buffer); works for all three examples above.

Comments