OCJP

Structure and Union in C Language

As earlier we learned Structure Example in C. Where we mentioned Structure is an user defined Data Type. C Language has another same User Defined Data Type called Union. Main Difference between Structure and Union is Memory Allocated to Structure and Union.

In Structure Each Member gets separate space. So that total size of Structure variable is sum of the member size. in our example 12 + 6 + 2= 20 bytes.

While union gets the memory equal to size of Biggest Member , in our case nm[12] is the biggest member. So Union variable will get 12 Bytes. But problem is that, We can not store the values of all the members at a time.

#include<stdio.h>
#include<conio.h>

struct Student
{
char nm[12]; //12 bytes
char gen[6]; // 6 bytes
int age;     //2 bytes
//Total Allocated :12 + 6 + 2 =20 Bytes
};


union UStudent
{
char nm[12];
char gen[6];
int age;
//Total Allocated :12 bytes
};

void main()
{
	struct Student S;
	union UStudent U;
	clrscr();
	printf("\Size of Structure Variable %d Bytes ",sizeof(S)); //20
	printf("\nSize of Union Variable %d Bytes",sizeof(U));//12
	getch();
}

Means you can access only one member at a time in Union.

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?