Size of structure containing char fields

Doug Gwyn gwyn at smoke.BRL.MIL
Tue Jul 24 04:23:23 AEST 1990


In article <1030 at lzaz.ATT.COM> bds at lzaz.ATT.COM (Bruce Szablak) writes:
>Given a structure that contains only char fields (possibly unsigned):
>	struct example1 { char a, b, c; };
>is ANSI restrictive enough [;-)] to force sizeof(example1) to be 3?

No; there may be padding at the end of the structure.

>Is anyone aware of existing compilers for which this wouldn't be true?

Yes.  Practically any word-oriented architecture would have padding.

>Is there a portability problem with the following structure where the
>array is intended to support a variable length array?
>	struct example2 { char a, b, c[1]; };

There is no problem with the declaration; however, care must be exerted
in using it for variable-sized allocations.  Karl Heuer (I think it was)
a few months ago gave a logical analysis in support of the view that the
C standard does permit this sort of trick if coded properly.  That is,
an attempt to enforce a bounds check on the array would be nonconforming
in such contexts.  I agree with the analysis, and have in fact used this
trick in code that was intended to be highly portable, but I don't
recall X3J11 specifically blessing this interpretation.



More information about the Comp.std.c mailing list