I’m trying to understand and use a union in C in a Linux environment.
Suppose I have the following union
union test {
int one;
long two;
} t1;
If I’m going to write t1.one to a network file descriptor (socket fd) then extra zeros will be written to the fd as the union chooses the biggest element, which is two; and it can get even worse with a union of structures. Can someone please show me how to overcome this?
No, if you write
test.oneto the network fd, you’ll write exactlysizeof (int)bytes.test.oneis anintobject; the fact that it happens to be a member of a union is irrelevant, as long as you don’t access the union as a whole.If you write the entire union, then of course you’ll write the full size of the union, which will be at least the size of its largest member.
So don’t do that.
Keep track of which member of the union is current (i.e., which member you most recently assigned a value to), and just use that member.
Then again, given the minimal information you’ve given us, it’s not clear that it makes sense to use a union at all.