Thursday, August 28, 2008

What are the differences between structure and union ?

The main difference between a structure and union is in allocation of memory. In a structure, every member will be allocated its own memory space. Whereas for a union, the total memory allocated will be the memory required to accommodate the largest member. Suppose, a structure and union are declared as given below :

struct tmpStruct {
char name[20];
int id;
float f;
}varStruct;

union tmpUnion {
char name[20];
int id;
float f;
}varUnion;


Here the variable 'varStruct' will be allocated with total number of bytes required by its members, along with padding bits if it is required (ie. sizeof(name) + sizeof(id) + sizeof(f) + Padding). So here each member will be having its own memory location. On the other hand, the variable 'varUnion' will be allocated only with the largest member of it(ie. sizeof(name) + Padding). As a result, for a union only the member which was last assigned can be accessed. For example, the following code may give undefined results:
varUnion.id = 50;
varUnion.f = 100.00f;
printf("%d\n", varUnion.id); // Gives undefined result as last assigned member was varUnion.f.

While the same code works fine for a structure
varStruct.id = 50;
varStruct.f = 100.00f;
printf("%d\n", varStruct.id); // Prints 50

0 comments: