Hi Silver,
Yes we can save memory using a union
Here is where unions are used:
Union may be useful when it is necessary to work with different representation of same binary data.
For example, you need to store color data as four 8-bit unsigned char numbers. At the same time, you have to store this color data as one 32-bit unsigned integer. Union allows to use both representation(struct with 4 unsigned char and unsigned integer) at the same time, using same block of computer's memory.
Union is used in case of libraries which return assorted data's. for example, say a stack library is present which can return an int or double depending on what is on top of stack.In such a case, the application layer should be able to receive from library either int or double. so in application layer we use union.
On most computers, the size of a pointer and an int are usually the same this is because both usually fit into a register in the CPU. So if you want to do a quick and dirty cast of a pointer to an int or the other way, declare a union.
[B] union intptr {
int i;
int * p;
};
union intptr x;
x.i = 1000;
*(x.p)=90; /* puts 90 at location 1000 */ [/B]
Another use of a union is in a command or message protocol where different size messages are sent and received. Each message type will hold different information but each will have a fixed part (probably a struct) and a variable part bit. This is how you might implement it..
[B] struct head {
int id;
int response;
int size;
};
struct msgstring50 {
struct head fixed;
char message[50];
}
struct struct msgstring80 {
struct head fixed;
char message[80];
}
struct msgint10 {
struct head fixed;
int message[10];
}
struct msgack {
struct head fixed;
int ok;
}
union messagetype {
struct msgstring50 m50;
struct msgstring80 m80;
struct msgint10 i10;
struct msgack ack;
}[/B]
In practice, although the unions are the same size, it makes sense to only send the meaningful data and not wasted space. A msgack is just 16 bytes in size while a msgstring80 is 92 bytes. So when a messagetype variable is initialized, it has its size field set according to which type it is. This can then be used by other functions to transfer the correct number of bytes.
[B] union messagetype ackmsg;
ackmsg.fixed.size = sizeof(msgack) ; /* 16 */[/B]
Hope this was useful to you and unwrapped your puzzle!!!!! 😉
-Arvind (slashfear)