2

I have been implementing a communication protocol in C++ and I have decided to model one packet in below given manner.

union control_pkt_u{
    struct pkt_parts_t{
        uint8_t header[3];                                // Control packet header
        uint8_t payload[NO_PYLD_BYTES_IN_CONTROL_PACKET]; // Control packet payload
    };
    uint8_t pkt_array[NO_BYTES_IN_PACKET];
};

As soon as I need to access to the elements of the union

pkt.pkt_parts_t.header[0] = APP_MSG_DEB; 

I receive an error during compilation:

invalid use of struct Manager::control_pkt_u::pkt_parts_t

Please can anybody tell me what I am doing wrong?

Mat
  • 202,337
  • 40
  • 393
  • 406
Steve
  • 805
  • 7
  • 27
  • 2
    `pkt_parts_t` is not a data member, it is a member type. You need to instantiate it. –  Feb 27 '18 at 10:02
  • 1
    your `control_pkt_u` has only one member which is an array of `uint8_t`s. What is the type of `pkt` anyhow? Please read about [mcve] – 463035818_is_not_an_ai Feb 27 '18 at 10:03
  • sorry if this is too direct: This error is a consequence of not understanding the difference between types and instances. I strongly suggest you to [grab a book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and review the basics, because this misunderstanding has many symptoms (mostly errors that can be avoided easily) – 463035818_is_not_an_ai Feb 27 '18 at 10:07
  • 2
    Chances are you don't want to use unions in the first place. – Ron Feb 27 '18 at 10:13

2 Answers2

6

Because you are just defining a struct in your control_pkt_u union and it is just a declaration, it is not initialised when you create an object from it. You need to declare it as a member like this and reach your member pkt_parts_.

union control_pkt_u {
    struct pkt_parts_t {
        uint8_t header[3];                                // Control packet header
        uint8_t payload[NO_PYLD_BYTES_IN_CONTROL_PACKET]; // Control packet payload
    } pkt_parts_;
    uint8_t pkt_array[NO_BYTES_IN_PACKET];
};

pkt.pkt_parts_.header[0] = APP_MSG_DEB;
xeco
  • 184
  • 14
2

You can change the struct definiation to this by using Anonymous structure:

struct {
    uint8_t header[3];                                // Control packet header
    uint8_t payload[NO_PYLD_BYTES_IN_CONTROL_PACKET]; // Control packet payload
} pkt_parts_t;

Then you don't need to change other code.

zheng bin
  • 61
  • 4