views:

45

answers:

2

Hi

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

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?

+1  A: 

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?

rmk
Thanks, I will take a look at that.
Boris
+1  A: 

See pragma pack in Visual Studio if you (also) use this compiler.

Iulian Şerbănoiu