Monday, 20 February 2012

What are the differences between a structure and a union? | C Programming

Structures and Unions are used to store members of different data types.
STRUCTURE UNION
a)Declaration: a)Declaration:
struct union
{ {
data type member1; data type member1;
data type member2; data type member2;
}; };
b)Every structure member is allocated
memory when a structure variable is defined.
Example:
b)The memory equivalent to the largest item is allocated
commonly for all members.
Example:
struct emp {
char name[5];
int age;
float sal;
};
struct emp e1;
Memory allocated for structure is 1+2+4=7 bytes. 1
byte for name, 2 bytes for age and 4 bytes for sal.
union emp1 {
char name[5];
int age;
float sal;
};
union emp1 e2;
Memory allocated to a union is equal to size of the
largest member. In this case, float is the largest-sized
data type. Hence memory allocated to this union is 4
bytes.
c)All structure variables can be initialized at a time
struct st {
int a;
float b;
};
struct st s = { .a=4, .b=10.5 };
Structure is used when all members are to be
independently used in a program.
c)Only one union member can be initialized at a time
union un {
int a;
float b;
};
union un un1 = { .a=10 };
Union is used when members of it are not required to be
accessed at the same time.