How do I access internal union members?

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 INTERNAL_STRUCTURE member from my code?

I thought I could just do this:

CORRHDR hdr;
hdr.INTERNAL_STRUCTURE.type = 1;

      

I am wrong. I can see the enums in the union, but nothing else. Can anyone explain the structure (or benefit) of this type for me?

+1


a source to share


4 answers


You have declared a named type INTERNAL_STRUCTURE

, but not an actual instance of that type. Try the following:

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);

      

+5


a source


You need to define an object of the type INTERNAL_STRUCTURE

before you can try to access it. Your union does not have one at the moment. Try:

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

      



...

+1


a source


You have 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;

      

0


a source


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

You need to define a variable of this structure type:

union Blob
{
  CHAR _filler[32];

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

CORRHDR hdr;
hdr.myStruct.type = 1;

      

0


a source







All Articles