sizeof(union) and #pragma pack()
Geoffrey Keating
geoffk@geoffk.org
Wed Sep 22 20:41:00 GMT 2004
"Dave Trollope, Diane Barrowman" <daveanddiane@kringlecottage.com> writes:
> Hi,
>
> The following code seems to cause the sizeof() function to return a
> size that is two bytes larger than I expected. Is this the right
> behaviour?
>
> struct a6 { unsigned long a; unsigned short b };
> #pragma pack(2)
> struct a10 {
> union {
> struct a6 emedded;
> int *ptr;
> }
> unsigned long junk;
> };
> #pragma pack()
>
> I was expecting sizeof(struct a10) to return 10 but it returns 12.
>
> If I move the #pragma pack(2) above the first struct definition,
> sizeof(struct a10) returns 10 as expected. This is presumably because
> the packing between the structure and the union is miscalculated from
> the structure defaulting to a padded 8.
>
> I'd like to know if this is the expected behaviour, or if this is
> something that needs fixing?
This is correct. sizeof(struct a6) is 8, and 'int *' is 4, and
8+4=12. This is necessary for correct behaviour if you say, for instance,
struct a6 x;
struct a10 y;
memcpy (&y.emedded, x, sizeof (x));
More information about the Gcc
mailing list