Structures and Unions in C

In C programming , a structure is a collection of heterogeneous elements under a same name.

Define

struct structureName 
{
    dataType member1;
    dataType member2;
    ...
};

Example

struct Person
{
    char name[20];
    int Number;
    float salary;
} person1, person2, p[20];

int main()
{
printf("enter name of person");
scanf("%s",&person1.name);
printf("enter id number");
scanf("%d",&person1.number");
printf("enter salary");
scanf("%f",&person1.salary);
}
return 0;
}

Output

enter name of person paras

enter id number 4819

enter salary 10000

Using same we can store/acess the data of person2 .

Why we use structure?

Suppose , you want to create or store the information of students data base

here if we are not using structure we need to create different variables for each student and this will increase size and complexity of the program

by using structure we can store easily and access the database more easily and efficiently

Unions

  • Unions are also a collection of heterogeneous elements
  • Unions are helpful when you want to store value in single member from different datatype variables
  • In unions only one member of union can be accessed at a time
  • Size of union is defined according to size of largest member data type.

Define

union union_name
{
    union_member1;
    union_member2;
    ...
    ...
    ...
    union_member_N;
};

Example

union mobile
{
  char name[50];
  int price;
} mobile1,mobile2;

int main();
printf("enter the brand name");
scanf("%s",%mobile1.name);

return 0;
}}

Output

enter brand name Samsung

 

Now you will be wondering whats the difference then? we can compile the same program using structure too, then how does it make a difference?

To understand the difference we need to look at the size of memory they are using

you can compare the size of strucuture and union using sizeof operator.

Hits: 108

Tags: No tags

Share your thoughts