difference between struct and union

struct and union are two c programing construct in c programing. The main difference between struct and union is “compiler allocates memory for all the members of struct while compiler allocates memory for largest size members of union. The members of struct can be used at the same time while we are supposed to access union members one at a time. consider below example.

#include<stdio.h>
struct mystruct {
short c;
int b;
}abc;
int main()
printf("%ld\n",sizeof(abc));
return 0;
}

In above example the size of mystruct will be equal to the size of short c and size of int b. assuming short and int to be size of 2 and 4 , the size should be 6. but when you can compile and run the above program we may get 8 due to padding bit inserted by compiler for data alignment requirement. if you donot know the data alignment you can follow the link “http://wikistack.com/packing-and-padding-in-c/“.

Now consider another example with union example as below.

#include<stdio.h>
union myunion {
short c;
int b;
int main(){
printf("%ld\n",sizeof(abc));
return 0;
}

The output of above program would be 4. As compiler allocates memory for only largest members of union. The same largest area is used for all the members of union.

#include<stdio.h>
union myunion {
int b;
char c;
int main()
union myunion un;
un.b=576;
printf("%c\n",un.c);
printf("%d\n",un.b);
return 0;
}

The output of above program:
@
576

Note:The assignment of on of union members affect the value of other members.



Related Contents to follow