member alignment in c struct-embedded union
I am modifying a bit of C code, that goes roughly like this:
typedef struct STRUCT_FOO {
ULONG FooInfo;
union {
ULONG LongData;
USHORT ShortData;
UCHAR CharData;
};
} FOO;
...
FOO foo;
ULONG dataLength = offsetof(FOO, CharData) + sizeof(foo.CharData);
Obviously, the code tries to figure out the number of interesting bytes in the struct, when using the CharData member of the union. My problem is, that the compiler warns about the union being unnamed. So I change it into
开发者_Go百科typedef struct STRUCT_FOO {
ULONG FooInfo;
union {
ULONG LongData;
USHORT ShortData;
UCHAR CharData;
} FooData;
} FOO;
But then of course I also need to change the last line. Will the following always yield exactly the same results as the original?
ULONG dataLength = offsetof(FOO, FooData) + sizeof(foo.FooData.CharData);
or is it possible, that CharData (or ShortData or LongData) will not be aligned at the beginning of the union?
-- edit: Thank you for your answers. The answer to this question actually provided me with the answer I needed: A pointer to a union object, suitably converted, points to each of its members (or if a member is a bitfield, then to the unit in which it resides), and vice versa..
Should I just choose one of the answers for this question as the accepted answer, anyway?
Have you investigated __attribute__
?
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Type-Attributes.html
Maybe you could make sure what you need is aligned by using this?
See pragma pack in Visual Studio if you (also) use this compiler.
精彩评论