Q:

Cast increases required alignment of target type

I am programming on ARM and have the following code snippet (in C):
struct data {
   int x;
   char y[640];
};
unsigned int offset = 819202;
char *buf; // buf is assigned an address elsewhere in the code
struct data * testdata = (struct data *)(buf + offset) 

I get the following compilation error:

error: cast increases required alignment of target type [-Werror=cast-align]

testdata pointer needs to point to the portion of memory that contains an array of data of type struct data. So I need a pointer so that later I can apply an index to testdata. Offset is hard coded in the program. buf is received as shared memory from another process.
For example, later in code I have:
testdata[index].x = 100;

I have seen some examples on SO but I'm not sure what is the correct way to handle this. Any suggestions ?

A:

The cast-align warning is triggered when you attempt to cast from a type with smaller alignment to a type with larger alignment.  In this case you got from a char which has alignment 1 and a struct data which (because it contains an int) has alignment 4 (assuming a int is 4 bytes).
Rather than having a pointer to a struct point into a character array, use memcpy to copy from the buffer into an instance of the struct.
struct data testdata;
memcpy(&testdata, buf + offset, sizeof(testdata));

