Structure within the union

I am trying to create a network application and I need to write one choice at a time, one, two or three. The union below writes 4 characters 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 little confused here, how can I build a selection of structures?

+3
source share
3 answers

Joining is equal to a large member because it must be able to store the largest member at any time. In this case, you have struct threeone that contains two arrays of two characters each, for a total of four characters, so any instance choicewill contain four characters.

+4
source

, . :

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;
}
+3

:

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

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

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

Please note that in your case sizeof(union choice_)it will always be equal to size struct three.

0
source

All Articles