In structure, memory space will be created for all members inside structure. In union memory space will be created only for a member which needs largest memory space. Consider the following code:
struct s_tag
{
int a;
long int b;
} x;
struct s_tag
{
int a;
long int b;
} x;
union u_tag
{
int a;
long int b;
} y;
union u_tag
{
int a;
long int b;
} y;
Here there are two members inside struct and union: int and long int. Memory space for int is: 4 byte and Memory space for long int is: 8
So for struct 4+8=12 bytes will be created while 8 bytes will be created for union. I run the following code to see a proof: C
#include<stdio.h>
struct s_tag
{
int a;
long int b;
} x;
union u_tag
{
int a;
long int b;
} y;
int main()
{
printf("Memory allocation for structure = %d", sizeof(x));
printf("\nMemory allocation for union = %d", sizeof(y));
return 0;
}
But I can see the following output:
Memory allocation for structure = 16
Memory allocation for union = 8
Why memory allocation for struct is 16 instead of 12? Is there any wrong in my understanding?