Code:
union A
{
int data1;
char data2;
unsigned char data3;
};
The variables data1, data2 and data3 share memory. The block of memory they share has the size of the largest datastructure in the union. In this example data1 is the largest datastructure and so a variable of type union A can store at most an integer type.
Since data1, data2 and data3 share the same block of memory, changing one of the variables implies changing the others too.
Assume N is the block of memory which is a variable of type union A. Also assume we are working on a machine where an integer is 16 bits. The member data1 of union A fits exactly in the memory block, it is of type int, but the other two variables are just the half of data1.
Code:
N - XXXX XXXX XXXX XXXX
---------------------------------------
data1 - XXXX XXXX XXXX XXXX
data2 - XXXX XXXX
data3 - XXXX XXXX