Address Alignment rules for structure variables

Hi,

This question might look naive, but I need to know address alignment rules used by O/S, hence posting this one.

I've following 2 structures :-

struct xyz {
char a;
int b;
char c;
}

struct abc {
char a;
char c;
int b;
}

If I print size of these 2 structures using sizeof() operator, it is 12 for xyz & 8 for abc. This is consistent on 32 as well as 64 bit machines (I'm using HP-UX).

Both structures have some no of elements of same type, only they differ in order of definition.

Then why is that size of struct xyz is 12 where as that of struct abc is 8 ?

What are precise rules for address alignment ?

Thanks in advance

I tried it on HP uX11 and get the same results, tried to swap the definitions of the structures but still gives the same output.

The first question has been covered, mostly...but it is due to the natural word size and alignment of the machine you are compiling on. However, because of this, I would have to say that there are no "precise rules" that can be assumed for every machine. If you want your code to be portable then you can not make any assumptions other than that the elements will be ordered in the same order as they are in the structure.

So, reading beyond your question a bit, I'd ask why you need to know these precise rules when such operands as "offsetof" and "sizeof" exist to give you this information.

The only unaligned data type is char, so if you mix any other types into your structure you may have alignment differences on various machines...therefore good code should either make so assumption and use offsetof to aquire the aligned location of the member, or should not not require the offset and make direct access to the members as provided by the compiler.