I have a question about union in c. The following code is the server side, we receive Signal2 from the client side, in the service function, can I check the signal type like this: data_p->header.type? and in the switch case, how could I pass the parameter to function printInfo(), the parameter of it is the pointer to the union, how to pass? And the last question is the pointer to the union, point to what? and what is inside of the union, when these three structs are allocated, how could they fit into the union(with the size of the large struct)?
union
{
Header header;
Signal1 signal1;
Signal2 signal2;
} Data;
struct Header
{
int type:
int protocol;
int clientId;
int serverId;
};
struct Signal1
{
int type:
int protocol;
int clientId;
int serverId;
char[80] something;
};
struct Signal2
{
int type:
int protocol;
int clientId;
int serverId;
int[100] something;
};
void service(Data* data_p) {
switch(data_p->header.type) {
case 1:
printInfo(&data_p->header);
case 2:
printInfo(data_p->header);
case 3:
data_p->signal2->something[5];
}
}
void printInfo(Data* data_p)
{
data_p->header.primitive;
}
In your example it looks like you want to rely on the fact that the type, protocol, clientId, serverId fields from Header, Signal1, Signal2 will be aligned the same way. But nothing in the C or C++ standard guarantees that AFAIK. So it would probably work with most C compilers but it is a hack, where such a hack is not necessary.
It seems like it would be better to do things as follows :
As for your last question if I understand it correctly, the union is allocated enough memory for the largest of it’s members, and aligned at the strictest of it’s members’ boundaries, and at any point in time contains valid data for one of it’s members (but nothing indicating which is the correct one). And the pointer to union is the address of the start of that memory area.