Unions
A union is a grouping different kind of data ans show it is user defined data type.So what is different between structure and union?
In structure individual member are having separate memory location,while in union all the members occupy same memory location.So only one memory location can be used to store all elements on union so that art a time only one member will have correct value in it.
For Example..
struct stud union stud
{ {
int sem; int sem;
char id[10]; char id[10];
char name[30]; char name[30];
}; };
struct stud s1; union stud u;
So, s1 will occupy 42 bytes, So u will occupy 30 bytes.As maximum number of bytes are 30 of name.
So in above example if we write
u.sem-5;
strcpy(id,"05b88");
strcpy(u.name,"nick");
printf("%d",u.sem);
printf("%d",u.id);
printf("%s",u.name);
will print garbage value for u.sem and u.id then for u.name it will print nick.
So in union only one member can be active and can have correct value at a time.Other members will have garbage values.
So This all for this blog.Comment your queries and get solution.
Thank you.
Comments