I had recently a bad experience with structure alignment. Bit more complicated than the example here I have structure pointers that are assigned to point to pre-defined array of elements (it was the easy way to translate messages between protocols/platforms). For example, I had :
typedef struct {
WORD16 var_index;
float data;
WORD16 command;
} FltArrayType;
FltArrayType *FltArrayPtr1;
…
WORD16 holding_regs[65535];
…
FltArrayPtr1 = (FltArrayType *) &holding_regs[500];
…
I assumed (wrong) that:
FltArrayPtr1->var_index should display data from holding_regs[500];
FltArrayPtr1->data should display data from holding_regs[501] and [502];
FltArrayPtr1->command should display data from holding_regs[503];
The actuality was:
FltArrayPtr1->var_index displayed data from holding_regs[500];
FltArrayPtr1->data displayed data from holding_regs[502] and [503];
FltArrayPtr1->command display data from holding_regs[504];
Basically, what ever I did, including following the examples given here, I could not set the pointers to point to the appropriate addresses they always pointed 32bits/4bytes apart.
Then I found this article: http://www.grok2.com/structure_packing.html
Quote (talking about using attribute((packed))) :
Note that this doesn’t seem to work right if you try to combine the typedef and the struct definition or if you combine variable declarations with the structure definition.
So I changed my structure definitions into:
struct FltArrayType {
WORD16 var_index;
float data;
WORD16 command;
} attribute ((packed));
typedef struct FltArrayType FltArrayType;
FltArrayType *FltArrayPtr1;
Now this did not solve the problem completely: variables defined as FltArrayType worked, but pointers of that type still did not (very strange).
The GNU toolkit mentions #pragma align X which does not work, and also the compiler switch -mstructure-size-boundary=X nor -structure-size-boundary=X where X is actually in bits.
The thing that finally set things straight was discovering -fpack-struct. Just open your make file and set the compiler options for both C and C++ files to:
APP_C_FLAGS=-fpack-struct
APP_CC_FLAGS=-fpack-struct
This along with attribute ((packed)) did fix all the problems that I had with both pointers and structures.
Hope this helps.