I am trying to read two integers, stored consecutively, from a memory block (i have a pointer void *block
pointing to the contents of the block) using memcpy
. The first one is read just fine using:
memcpy(&test, block, sizeof(int));
I try to read the second using:
memcpy(&test, block + sizeof(int), sizeof(int));
(Of course i am having those stataments in different execution instances of the program, so the problem is not that test is being overriden)
but i fail to get the correct result! What am i doing wrong here?
This is nonstandard:
void *block = ...;
block + sizeof(int); // where does this point to?
If you want to do pointer arithmetic, cast to a type of known size first (the pointer addition is implicitly multiplied by the size of the underlying type, and sizeof(unsigned char)
is always 1):
void *block = ...;
(unsigned char *) block + sizeof(int);
Or use the even easier version,
void *block = ...;
(int *) block + 1;
So the final code is:
int test;
void *block = ...;
memcpy(&test, block, sizeof(test));
// do something...?
memcpy(&test, (int *) block + 1, sizeof(test));
Or a simpler version,
int test[2];
void *block = ...;
memcpy(&test, block, sizeof(test));
Don't do the following:
test = *(int *) block;
It will crash on some systems (typically SIGBUS) if block
is unaligned.