Different Structure Union - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Sunday 5 November 2017

Different Structure Union

StructureUnion
In structure each member get separate space in memory. The total memory required to store a structure variable is equal to the sum of size of all the members. In above case 7 bytes (2+1+4) will be required to store structure variable s1.In union, the total memory space allocated is equal to the member with largest size. All other members share the same memory space. This is the biggest difference between structure and union.
We can access any member in any sequence.

s1.rollno = 20;
s1.marks = 90.0;
printf(“%d”,s1.rollno);

The above code will work fine but will show erroneous output in the case of union.
We can access only that variable whose value is recently stored.

s1.rollno = 20;
s1.marks = 90.0;
printf(“%d”,s1.rollno);

The above code will show erroneous output. The value of rollno is lost as most recently we have stored value in marks. This is because all the members share same memory space.
Each member within a structure is assigned unique storage area of location.Memory allocated is shared by individual members of union.
The address of each member will be in ascending order This indicates that memory for each member will start at different offset values.The address is same for all the members of a union. This indicates that every member begins at the same offset value.

Like structure, Union in c language is a user defined datatype that is used to hold different type of elements. But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares memory of largest member.

Syntax to define Union :

    union union_name
    {
    data_type member1;
    data_type member2;
    .
    .
    data_type memeberN;
    };


Example :

    union employee
    {
    int id;
    char name[50];
    float salary;
    };

Explanation :
Here the largest memory space will be of size 50byte(1*50) i.e of char name[50]

Example :

    #include <stdio.h>
    union employee
    {
    int id;
    char name[20];
    }e1; //declaring e1 variable for union

    int main( )
    {
    //store employee information
    printf(“Enter id : ”);
    scanf("%d",&e1.id);

    printf(“Enter name : ”);
    scanf("%s",e1.name);

    //printing employee information
    printf( "Employee id : %d\n", e1.id);
    printf( "Employee name : %s\n", e1.name);
    return 0;
    }


Output :
Enter id : 20
Enter name : abc
Employee id : 1819043176
Employee name : abc

No comments:

Post a Comment

Post Top Ad