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:
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):Or use the even easier version,
So the final code is:
Or a simpler version,
Don’t do the following:
It will crash on some systems (typically SIGBUS) if
blockis unaligned.