STRUCTURES
|
UNION
|
Struct keyword is
used to declare the structure
|
Union keyword is
used to declare the Union
|
Structure variable
will allocate memory for all the structure members separately.
|
Union variable will
allocate common memory for all the union members.
|
Example:
struct Employee{
int age;
char name[50];
float salary;
};
|
Example:
union Employee{
int age;
char name[50];
float salary;
};
|
Structures will
occupy more memory space.Memory_Size = addition of all the structure members
sizes.
Memory_Size = int + char array [50] + float Memory_Size = 2 + 50 + 4 Bytes Memory_Size = 56 Byte |
Union will occupy
less memory space compared to structures.Memory_Size = Size of the largest
Union member. From the above example, Largest Union member is char array so,
Memory_Size = 50 Bytes
|
It allows us to
access any or all the members at any time.
|
It allows us to
access only one union member at a time.
|
C Program to find Difference between Structure and Union
In this program, we
are going to declare the structure and union with same data type members and
then we are going to calculate the size of union and structure using sizeof function.
CODE
/* C Program to find difference
between Structure and Union */
#include <stdio.h>
struct Employee
{
int age;
char Name[50];
char Department[20];
float Salary;
};
union Person
{
int ag;
char Nam[50];
char Departent[20];
float Salar;
};
int main()
{
struct Employee emp1;
union Person Person1;
printf(" The Size of Employee Structure = %d\n", sizeof (emp1)
);
printf(" The Size of Person Union = %d\n", sizeof (Person1));
return 0;
}
No comments:
Post a Comment