Since buf
is a pointer to char
, when you write (struct data *) (buf + offset)
, you are saying “Take this pointer to some character, and make it a pointer to struct data
.” However, a struct data
is required to be aligned to a multiple of four bytes1, but your buf+offset
could have any alignment. If buf+offset
has the wrong alignment, it cannot be made into a correct pointer to struct data
, and your compiler is advising you about this problem.
The solution is to ensure that you have an aligned address that may be used as a pointer to a struct data
. Two ways to do this are:
- Define one or more
struct data
objects, as with struct data MyData;
or struct data MyArray[10];
.
- Allocate memory for
struct data
objects, as with struct data *MyPointer = malloc(SomeNumber * sizeof *MyPointer);
.
With any of the above, the compiler will ensure that the memory is properly aligned for a struct data
object. The former would generally be used only to work with the struct data
immediately and then discard it—it does not produce an object that you can return from a function. The latter is used when you want to return the resulting struct data
from a function.
Once you have these struct data
objects, you need to put data into them. Preferably, you would read data into them directly instead of into buf
. However, if your software design does not facilitate that, you can copy the data from buf
into the struct data
objects, as with one of:
memcpy(&MyData, buf+offset, sizeof MyData);
memcpy(MyArray, buf+offset, sizeof MyArray);
memcpy(MyPointer, buf+offset, SomeNumber * sizeof *MyPointer);
##Footnote##
1 Four is typical for a structure containing an int
and is assumed for this example. We know the alignment requirement is greater than one due to the compiler message.