tags:

views:

133

answers:

4

I have a union that is defined like this:

typedef union {
  enum {
    REVISION = 0,
    CURRENT_VERSION = REVISION
  };

  enum FLAGS{
    FLAG_DEFAULT               = 0x00000000,
    FLAG_EOD                   = 0x00000001,
    FLAG_OUTOFORDER            = 0x00000002
  };

  CHAR _filler[32];

  struct INTERNAL_STRUCTURE {
    UINT16 type;
    UINT16 flags;
  };
}CORRHDR

How do I access the member's of INTERNAL_STRUCTURE from my code?

I've thought I could just do this:

CORRHDR hdr;
hdr.INTERNAL_STRUCTURE.type = 1;

I'm wrong. I can see the enums in the union, but nothing else. Could someone explain the structure (or benefit) of this type to me?

+4  A: 

You have declared the type called INTERNAL_STRUCTURE, but not an actual instance of that type. Try this:

typedef union {
  //...
  CHAR _filler[32];
  struct {
    UINT16 type;
    UINT16 flags;
  } INTERNAL_STRUCTURE;
}CORRHDR;

Then to access the field:

CORRHDR ch;
printf("%u\n", ch.INTERNAL_STRUCTURE.type);
Greg Hewgill
[I'm porting from a unix system to windows]. Could defining a struct in this manner (inside the union with no instance name) just be developer reference for the binary data contained in the union?
scottm
Yes, with the declaration as given, you could access the data inside using something like: reinterpret_cast<CORRHDR::INTERNAL_STRUCTURE *>(ch._filler)->type but that seems awkward.
Greg Hewgill
+1  A: 

You need to define an object of type INTERNAL_STRUCTURE before you can try to access it. Your union as of now does not have one. Try:

struct INTERNAL_STRUCTURE {
    UINT16 type;
    UINT16 flags;
  };
struct INTERNAL_STRUCTURE is;

...

dirkgently
A: 

You defined a type named INTERNAL_STUCTURE

not an instance named INTERNAL_STRUCTURE.

typedef union {
  enum {
    REVISION = 0,
    CURRENT_VERSION = REVISION
  };

  enum FLAGS{
    FLAG_DEFAULT               = 0x00000000,
    FLAG_EOD                   = 0x00000001,
    FLAG_OUTOFORDER            = 0x00000002
  };

  CHAR _filler[32];

  struct {
    UINT16 type;
    UINT16 flags;
  } INTERNAL_STRUCTURE;
}CORRHDR;
null
A: 

Also, you define your struct but don't use it!

You need to define a variable of that struct type:

union Blob
{
  CHAR _filler[32];

  struct INTERNAL_STRUCTURE {
    UINT16 type;
    UINT16 flags;
  } myStruct;
};

CORRHDR hdr;
hdr.myStruct.type = 1;
Joce