Dev Bag
Dev Bag

Reputation:

Struct inside union

I'm trying to build network application and I need to be able to write one choice at a time, one, two or three. The below union writes 4 chars to the network even if I used only struct one.

union choice_
{
    struct one_
    {
        unsigned char one[2];
    }src;   
    struct two_
    {
        unsigned char two[2];
    }two;
    struct three
    {
        unsigned char one[2];
        unsigned char two[2];
    }three;
}choice;

Can't I just write choice.one

I'm a bit confused here, how can I build a choice of structs?

Upvotes: 3

Views: 7222

Answers (3)

hroptatyr
hroptatyr

Reputation: 4809

You can:

union choice_ u;
...
write(<fd>, u.one, sizeof(u.one));

or if it's two

union choice_ u;
...
write(<fd>, u.two, sizeof(u.two));

or in the third case

union choice_ u;
...
write(<fd>, u.three, sizeof(u.three));

Note however that in your case sizeof(union choice_) will always equal the size of struct three.

Upvotes: 0

Lundin
Lundin

Reputation: 213832

The union does not help you at all, but rather obfuscates the code and increases the chance of insertion of unwanted padding bytes. Instead, do like this:

typedef struct
{
  char data[2];
} choice_t;

...

void write_bytes_to_network (const choice_t* choice);

...

choice_t one = ...;
choice_t two = ...;

switch(something)
{
  case 1: 
    write_bytes_to_network (&one);
    break;

  case 2:
    write_bytes_to_network (&two);
    break;

  case 3:
    write_bytes_to_network (&one);
    write_bytes_to_network (&two);
    break;
}

Upvotes: 3

Caleb
Caleb

Reputation: 124997

A union is as large as its largest member because it has to be able to store the largest member at any time. In this case, you've got struct three which contains two arrays of two characters each, for a total of four characters, so any instance of choice is going to be four characters long.

Upvotes: 4

Related Questions