Thursday, March 31, 2016

Difference between Structures and Unions

Structure and union both are user defined data types. The main difference between structure and union is that union uses same memory location for all the member variables hence the size of the union is the size of the largest member variable but structure uses different memory location for all the members. Let’s take an example:
union my_union
{ int my_int;
char my_char2;
char my_char1; } my_union;
int my_int;
struct my_struct { char my_char1;
} my_struct;
char my_char2;
Now if we execute sizeof function over my_struct and my_union then we will see that the output as 4 for union and 6 for structure. As for structure it is simple 4 for integer and 2 for 2 character variables but if for union it happens because of the union’s property of sharing memory location to all members. Union allocates memory equal to the size of the member variable which takes largest in the memory. Here since integer takes 4 bytes and character takes 1 byte each that’s why it takes 4 bytes of memory hence it outputs 4.

No comments: