简体   繁体   中英

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!

The problem is your typedef statements. RF12Message::data is not a union of 40 uint8_t s and a MessageNodeFound ; it is a datatype consisting of those things.

A similar problem will affect your declaration of MessageNodeFound . Remove both typedef s, and I think it should work.

You have too many typedef s in your code. Try this:

http://codepad.org/frysgQte

For C++

The typedef declarations just declare a type. There is no data member called 'MessageNodeFound' or 'data' also for that matter.

This should give you an idea

typedef struct 
{ 

   typedef union  
   { 
      char raw[40]; 

      typedef struct 
      { 
         int nodeId; 
         char hierachyDepth; 
      } MessageNodeFound;

      MessageNodeFound m;

   } Data; 
   Data d;
} RF12Message;

int main(){
   RF12Message msg; 

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

   //or indirectly: 

   msg.d.m.nodeId = 3; 
   msg.d.m.hierachyDepth = 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM