Complete Computer Knowledge Portal

Thursday, April 11, 2013

Difference Between Structure and Union



Characteristics
Structure
Union
Definition
A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure.
A union is a special data type that enables to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time
Declaration
typedef struct {
          char name[64];
          char course[128];
          int age;
          int year;
  } student;
union Data
{
   int i;
   float f;
   char  str[20];
} data;  
Memory Allocation
In a structure, all of its data members are stored in contiguous memory locations. The size of an object of a struct is, therefore, the size of the sum of all its data members.

Example for Structure:

struct tech
{
char p;
int x;
float Q;
int y;
}D;

memory allocated for D will be  1+2+4+2= 9 bytes

A union is a class all of whose data members are mapped to the same address within its object. The size of an object of a union is, therefore, the size of its largest data member.

Example for union :

union tech
{
char p;
int x;
float q;
}N;

the memory allocated for union will be  4 bytes (that is largest size among members)
Uses
Structures are used where an "object" is composed of other objects.
Unions are typically used in situation where an object can be one of many things but only one at a time.
Values Assignment
In Structure Values can be assigned to every member at the same time.
In Union only one member can assign values at a time.
Data Type
It is User Defined Data Type
It is Derived Type Data Type.

No comments:

Post a Comment