Structure padding
Clive
clive at ixi.UUCP
Thu Apr 13 16:31:01 AEST 1989
In article <124 at paix.ikp.liu.se> pekka at paix.ikp.liu.se (Pekka Akselin [The Mad Midnight Hacker]) writes:
>>>[...]
>>>I need to know if I can safely assume that there will not be any
>>>padding between the arrays.
>
>How about this???
>
>union {
> struct foo {
> char Bar[3];
> char Baz[6];
> char Frotz[4];
> } fred;
> char SomeString[3 + 6 + 4];
>} Strings;
>
>#define bar Strings.Bar
>#define baz Strings.Baz
>#define frotz Strings.Frotz
>
>Would there be padding between the Bar, Baz and Frotz arrays in this case?
Yes there would. The size of the union is the maximum of the sizes of its elements.
Suppose that the compiler padded everything to 32-bit boundaries. Then your
declaration is effectively:
union {
struct foo {
char Bar[3];
char pad1[1];
char Baz[6];
char pad2[2];
char Frotz[4];
} fred;
char SomeString[3 + 6 + 4];
} Strings;
and the memory layout is:
Strings+: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
fred: --Bar-- # ------Baz------- ##### ---Frotz---
SomeString: 0 1 2 3 4 5 6 7 8 9 10 11 12 ########
where # indicates memory via this union element.
The answer to the original posting is "No". The only way to do it is some
technique which declares a single array and then breaks it up (e.g. via
#defines).
--
Clive D.W. Feather clive at ixi.uucp
IXI Limited ...!mcvax!ukc!acorn!ixi!clive (untested)
+44 223 462 131
More information about the Comp.lang.c
mailing list