Difference Between Structure and Union - C-Tutorial

Latest

Thursday, 20 October 2016

Difference Between Structure and Union

Difference Between Structure and Union


STRUCTURE

UNION
Members of structure do not share memory. So A structure need separate memory space for all its members i.e. all the members have unique storage.
A union shares the memory space among its members so no need to allocate memory to all the members. Shared memory space is allocated i.e. equivalent to the size of member having largest memory.
Members of structure can be accessed individually at any time.
At a time, only one member of union can be accessed.
To define Structure, ‘struct’ keyword is used.
To define Union, ‘union’ keyword is used.
All members of structure can be initialized.
Only the first member of Union can be initialized.
Size of the structure is > to the sum of the each member’s size.
Size of union is equivalent to the size of the member having largest size.
struct struct_name
{
structure ele 1;
structure ele 2;
———-
structure ele n;
}struct_variable_name;
union union_name
{
union ele 1;
union ele 2;
———-
union ele n;
}union_variable_name;
Change in the value of one member can not affect the other in structure.
Change in the value of one member can affect the value of other member.

/* Example program to show the difference between structure and union */

#include<stdio.h>

struct demo1
{
            char a;
            int b;
            float c;
            double d;
}d1;

union demo2
{
            char a;
            int b;
            float c;
            double d;
}d2;

main()
{
            clrscr();
            printf("\n Memory Size of Structure = %d Bytes",sizeof(d1));
            printf("\n Memory Size of Union     = %d Bytes",sizeof(d2));
}

No comments:

Post a Comment