Steve
Steve

Reputation: 849

Accessing union elements in C++

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?

Upvotes: 2

Views: 785

Answers (2)

zheng bin
zheng bin

Reputation: 61

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.

Upvotes: 2

xeco
xeco

Reputation: 184

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;

Upvotes: 6

Related Questions