Structure padding
Lloyd Kremer
kremer at cs.odu.edu
Mon Apr 10 06:02:01 AEST 1989
In article <440 at front.se> zap at front.se (Svante Lindahl) writes:
>Consider a struct consisting of a few character arrays, for example:
>
> stuct foo {
> char bar[3];
> char baz[6];
> char frotz[4];
> } fred;
>
>I need to know if I can safely assume that there will not be any
>padding between the arrays.
>(Note: I'm not talking about padding at the end of the struct; there
>will often be padding after the last array to make the size of the
>struct be a multiple of 2 or 4 bytes.)
It seems like a very unsafe thing to assume in code that is intended
to be maximally portable. The dimension '3' is especially worrisome
in this regard. However, there is a way to guarantee "no internal padding"
in a portable way.
You would simply define one big array (a C array is guaranteed to be
contiguous), and do the internal indexing yourself. There should be no
performance degradation since the compiler would arrange for such indexing
anyway. Also, some well-chosen macros could make using the strings easier.
How about:
#define bar_siz 3
#define baz_siz 6
#define frotz_siz 4
char fred[bar_siz + baz_siz + frotz_siz];
#define bar (fred + 0)
#define baz (fred + bar_siz)
#define frotz (fred + bar_siz + baz_siz)
/* the parentheses are vital to correct operation */
Now 'bar', 'baz', and 'frotz' can be treated just like normal character
arrays for accessing and indexing. But beware the sizeof() operator!
The only *real* array is 'fred', which will not be directly referenced in the
code. Thus,
sizeof(fred) == 13
but
sizeof(bar) == sizeof(baz) == sizeof(frotz) == sizeof(char *)
Capitalizing all the #define'd objects might help in remembering this pitfall.
Hope this helps,
Lloyd Kremer
Brooks Financial Systems
{uunet,sun,...}!xanth!brooks!lloyd
More information about the Comp.lang.c
mailing list