Optimal structure field ordering

Alan J Rosenthal flaps at csri.toronto.edu
Thu Jul 7 02:39:02 AEST 1988


On optimizing space by ordering the struct fields by the sizes of the
elements, nevin1 at ihlpf.UUCP (00704a-Liber,N.J.) writes:

>This is not (necessarily) true!  For instance:
>
>sizeof(long) === 8
>sizeof(short) === 5
>sizeof(char) === 1
>
>Also suppose that alignment for shorts and longs occurs on even addresses
>(two byte boundaries), while chars can align on single byte boundaries.

Aha!  This is inconsistent.  If shorts must be even-aligned,
sizeof(short) would have to report 6, not 5.  Consider an array 5 of
short, which must have size 29 or 30 to allow alignment, and which also
must have sizeof(array) == 5 * sizeof(short).

Going through your example again, you will see that, if sizeof(short)
is 6 and thus a wasted byte follows all shorts, it is still most
space-efficient to put the chars after the shorts.

ajr

--
- Any questions?
- Well, I thought I had some questions, but they turned out to be a trigraph.




More information about the Comp.lang.c mailing list