Search code examples
c++cdata-structuresstructunions

c(++) union Data structure


I'm programming for a µC, i have following data Structure:

typedef struct
{
  RF12Head head;

  typedef union 
  {
    uint8_t raw[40];

    typedef struct
    {
      node_id nodeId;
      uint8_t hierachyDepth;
    } MessageNodeFound;
  } data;

} RF12Message;

A RF12Message contains a header an an data part. Now i want to have different message formats.

I want to be able to do something like this:

RF12Message msg;

memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly

//or indirectly:

msg.data.MessageNodeFound.nodeId = 3;
msg.data.MessageNodeFound.hierachyDepth = 2;

but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why?

thank you!


Solution

  • You have too many typedefs in your code. Try this:

    http://codepad.org/frysgQte