Reputation: 47
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.
Upvotes: 0
Views: 2027
Reputation: 104539
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.
Upvotes: 4
Reputation: 409176
The major problem here is this part
memcpy (&buffer, ...);
// ^
First of all, if you want an "array" or int
then why don't you use a pointer to int
? You can always cast it to a generic void *
later. This will solve one problem, which is the pointer arithmetic you attempt to do in the second memcpy
call.
Going back to my highlighted part, using the address-of operator for buffer
is wrong and will pass a pointer to where the variable buffer
is stored, not the address where buffer
is pointing. Drop the address-of operator there.
To sum it up:
int *int_buffer = malloc(sizeof *int_buffer * 2);
memcpy(int_buffer, &int1, sizeof int1); // or &int_buffer[0]
memcpy(int_buffer + 1, &int2, sizeof int2); // or &int_buffer[1]
void *buffer = int_buffer;
For your printing, you only tell printf
to print the very first int
element. If you want to print both int
elements you need to tell printf
to do that.
Upvotes: 1