Re: Size of structs containing unions
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Fri, 30 Sep 2005 08:57:39 GMT
"luke" <lroluk1@xxxxxxxxx> writes:
> in Visula C++ 6.0 I have declared a struct like this:
>
> typedef struct _WRITE_INPUT {
Don't use identifiers starting with an underscore; they're reserved to
the implementation. (It's slightly more complex than that, but it's
safest just to avoid them.)
> ULONG DeviceNumber;
> ULONG RegisterNumber;
> union {
> USHORT ShortData;
> UCHAR CharData;
> };
> } WRITE_INPUT;
>
> I can't understand why, sizeof(WRITE_INPUT) returns 12. It should
> return 10, shouldn't it?
>
> sizeof(ULONG) = 4
> sizeof(ULONG) = 4
> sizeof(USHORT) = 2 (longest union field)
>
> 4 + 4 + 2 = 10
The compiler is free to add padding after any member of a structure.
In this case, it's probably adding 2 bytes of padding at the end to
make the size of the structure a multiple of 4, so the ULONG members
will be aligned properly if you have an array of structures.
Incidentally, the names ULONG, USHORT, and UCHAR aren't particularly
helpful. I presume they're typedefs (or macros?) for unsigned long,
unsigned short, and unsigned char, respectively. Why not just use the
names directly?
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- References:
- Size of structs containing unions
- From: luke
- Size of structs containing unions
- Prev by Date: Re: Size of structs containing unions
- Next by Date: offsetof
- Previous by thread: Re: Size of structs containing unions
- Next by thread: Re: Size of structs containing unions
- Index(es):
Relevant Pages
|