However, this does build on the assumption that the first member of struct will be stored immediately after word boundary. Is it always so?
Yes.
When a structure type is defined, the alignment requirement of the structure will be at least the strictest alignment requirement of its members. For example, if a structure has members with alignment requires of 1 byte, 8 bytes, and 4 bytes, the alignment requirement of the structure will be 8 bytes. The compiler will figure this out automatically when the structure is defined. (Technically, the C standard might permit the compiler to give the structure an even greater alignment—I do not see any rule against it—but that is not done in practice.)
Then, whenever the C implementation reserves memory for a structure object (as when you define an object of that type, such as struct foo x
), it will ensure the memory is aligned as required for that structure. That results in the alignment requirements of the members being satisfied too. When a program allocates memory with malloc
, the returned memory is always aligned as necessary for any object of the requested size.
(If you do any “funny stuff” in a program to set your own memory locations for objects, such as placing one in the middle of memory allocated with malloc
, you are responsible for getting the alignment right.)
Further, the structure will be padded at the end if necessary so that its total size is a multiple of that alignment requirement. Then, in an array of those structures, each successive element of the array will begin at a properly aligned location too.