Thursday, July 14, 2011

Difference Between Structure And Union

 DIFFERENCE BETWEEN STRUCTURE AND UNION

Difference Between Structure And Union


Structure
Union
1
Structures are used to group a number of different variables together which enables us treat a number of different variables stored in different place in memory.
Union are used to group a number of different variables together which enables us to treat the same space in memory as a number of different variables.
2
Syntax:
struct structure_name
{
Data_type member;
........
};
struct structure_name  structure_variable;
Syntax:
union structure_name
{
Data_type member;
........
};
union structure_name  structure_variable;
3
Example:
#include<stdio.h>
#include<conio.h>

void main()
{
  struct try
  {
      int i;
      char ch[2];
  };

  struct try t;

  t.ch[0]=50;
  t.ch[1]=30;
  t.i=512;

  printf("t.i=%d\n",t.i);
  printf("t.ch[0]=%d\n",t.ch[0]);
  printf("t.ch[1]=%d",t.ch[1]);
}
Output:
t.i = 512
t.ch[0] = 50
t.ch[1] = 30
Reason:
t.ch[0] , t.ch[1] and t.i values are stored in different memory locations there for, no values are changed
Example:
#include<stdio.h>
#include<conio.h>

void main()
{
union try
{
      int i;
      char ch[2];
};

union try t;

  t.ch[0]=50;
  t.ch[1]=30;
  t.i=512;

printf("t.i=%d\n",t.i);
printf("t.ch[0]=%d\n",t.ch[0]);
printf("t.ch[1]=%d",t.ch[1]);
}
Output:
t.i = 512
t.ch[0] = 0
t.ch[1] = 2
Reason:
Values of t.ch[0] and t.ch[1] i.e. 50 and 30 , is changed to 0 and 2 respectively after t.i is assigned with 512. This happens because t.ch[0] and t.ch[1] share the same memory.

0 comments:

Post a Comment