C / C++ FAQs & Programming Resources - ProkutFAQ : StructureVsUnion

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links

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

 Comments [Hide comments/form]
Hi I would like to add one more difference:
Suppose int is 4bytes and char is 1 byte in memory.

struct tmpStruct {
char jatin :1;
int rajpal :2;
}varStruct

union tmpUnion {
char jatin :1;
int rajpal :2;
}varUnion;

Now the

sizeof(varStruct) would be 1 byte coz the int and char are using 3 bit space so for storage they need some atleast one word i.e. 1 byte.

sizeof(varUnion) would be 4 bytes i.e. the size of greatest element which is integar in this case.

Plz let me know whether my explanation is sufficient or not.
rajpal_jatin@yahoo.co.in:-)
-- 217.73.15.6 (2007-03-07 10:20:40)
I think the size of varStruct would be 5(or more i.e,padding size) coz sizeof(int)+sizeof(char)+padding size.. Here it is 4(or 2)+1.. So obviously struct will be having a greater size than union.. this is already discussed in this page itself..!
-- AishWarya (2007-12-22 10:10:42)
Page was generated in 0.0275 seconds