Structures and Unions

Structure in 'C' language  :
Introduction:
  • Structure is a user defined data type of 'C'. 
  • It is used to store different types of elements as per user requirements. 
  • For example structure student should contain Student details such as Roll_no, name, class, percentage, address, contact_no etc. 
  • This information can be stored into a single tuple using structure.
Definition :
  • Structure can be defined using struct keyword. 
  • Syntax :
     typedef struct struct_name
    {
       data_type1 member1;
       data_type2 member2;
       .
       .
       .
     };

  • Example :
typedef struct student
{
    int roll_no;
    char name[40];
    char class[15];
    float percentage;
};

 typedef is used to define new data type in 'C'.

Initialization :
  • Structure members can not be  initialized until and unless we create object of particular structure type. 
  • Thus before initializing structure members we must create their objects.
  • Syntax to create structure object is:
          struct struct_name obj_name;
  • For example struct student s1; now s1 is an object of type student. 
  • Dot(.) operator is used to initialize and access structure members. 
  • For example : Object s1 can be initialized as follow 
        s1={101,"Nisha","FYBCS",78.8};
  • Sample program to illustrate structure :
#include<stdio.h>
typedef struct student
{
 int roll_no;
 char name[30];
 char cls[15];
 float perc;
};

int main()
{
 struct student s1={101,"Nisha","FYBCS",78.5};
 struct student s2={102,"Meena","FYBCS",85.2};
 printf("\n Structure members are: \n");
 printf("Details of Student1 :");
 printf("\n Roll number: %d\n Name: %s\n class: %s\n percentage: %f",s1.roll_no,s1
 printf("\n\n Details of Student2 are:\n ");
 printf("Roll number: %d\n Name:%s\n Class: %s\n Percentage : %f",s2.roll_no,s2.na
 return 0;
}

Output :
 Structure members are:
 Details of Student1 :
 Roll number: 101
 Name: Nisha
 class: FYBCS
 percentage: 78.500000

 Details of Student2 are:
 Roll number: 102
 Name:Meena
 Class: FYBCS
 Percentage : 85.199997

  • Program to read and display structure values from user.
#include<stdio.h>
#include<string.h>
struct emp
{
int eno;
char name[30];
int salary;
};

int main() 
{
struct emp e1;
//accepting details from user
printf("\n Enter employee ID : ");
scanf("%d",&e1.eno);
printf("\n Enter employee name : ");
gets(e1.name);
printf("\n Enter salary : ");
scanf("%d",&e1.salary);
printf("\n \nGiven details are : \n");
printf("Emp ID : %d\n Name : %s\n Salary : %d",e1.eno,e1.name,e1.salary);
return 0;
}

Output :
Enter employee ID : 101
Enter employee name : Minal
Enter salary : 12500

Given details are :
Emp ID : 101
Name : Minal
Salary : 12500

Note : Since now gets() is removed  from C above program may not work on higher versions.


Nested Structures :
  • We can define one structure inside the another structure called as nested structure. 
  • Syntax for declaring nested structure is : 
struct stuct_name
{
    data_type  member1;
    data_type member2;
    ______
    struct inner_struct_name
   {
       data_type member1;
       data_type member2;
      __________
    };
};

For example :
struct person
{
   char name[30];
   struct address
   {
       char city[30];
       int pin[6];
    };
};

  • To access members of nested structure we have use 
  • syntax as outer_struct_obj.inner_struct_obj.member;


Program to illustrate nested Structures :

#include<stdio.h>
struct Person
{
    char name[50];
    struct addrs
   {
      int pcode;
      char city[20];
    }a;
};

int main() 
{
struct Person p={"Joshi",{411001,"Pune"}};
printf("\n Details are : \n");
printf("\n Name : %s",p.name);
printf("\n Pincode : %d",p.a.pcode);
printf("\n City : %s",p.a.city);
return 0;
}

Output :
Details are :
Name : Joshi
Pincode : 411001
City : Pune

Note : Here struct addrs is a nested structure with object a and outer structure Person has object p. Thus we write p.a.city to access nested city member and same for pcode.

 

 Array of Structures :
  • In above section we have created two different objects of student to store details about them respectively. 
  • But how can we store details of whole class or say fifty students. 
  • Should we create fifty different objects of type struct student. 
  • No, solution to this problem is to create array object of size fifty of struct student. Such a object is called as array of structure. 
  • To be more clear about it consider following program to accept and store details of 'n' number of students :

#include<stdio.h>
#define MAX 50
struct student
{
int rno;
char name[20];
char clas[20];
float perc;
};
int main()
{
int n,i;
struct student s[MAX];
printf("Enter how many students?");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\n Enter roll number of student %d: ",i+1);
scanf("%d",&s[i].rno);
printf("\n Enter name of student %d: ",i+1);
scanf("%s",s[i].name);
printf("\n Enter class of student %d: ",i+1);
scanf("%s",s[i].clas);
printf("\n Enter percentage of student %d: ",i+1);
scanf("%f",s[i].perc);
}
printf("\n\n Entered details are : \n");
for(i=0;i<n;i++)
{
printf("\n\n Roll number : %d",s[i].rno);
printf("\n Student Name : %s",s[i].name);
printf("\n Class : %s",s[i].clas);
printf("\n Percentage : %f",s[i].perc);
}
return 0;
}

Output :
Enter how many students? 3 

Enter roll number of student1: 51
Enter name of student1: John
Enter class of student1: FYBCS
Enter percentage of student1: 65.2

Enter roll number of student2: 52
Enter name of student2: Smita
Enter class of student2: FYBCA
Enter percentage of student2: 78

Enter roll number of student3: 53
Enter name of student3: Harry
Enter class of student3: TYBBA
Enter percentage of student3: 82.3

Entered details are:

Roll number : 51
Student name : John
Class : FYBCS
Percentage : 65.2

Roll number : 52
Student name : Smita
Class : FYBCA
Percentage : 78

Roll number : 53
Student name : Harry
Class : FYBBA
Percentage : 82.3


Structures and functions :
  • We have learned both concept of structure as well as function. 
  • We can structure as an argument to a function. 
  • Let's see following program to pass each member of structure as a separate argument :
#include<stdio.h>
struct calculator
{
 int num1;
 int num2;
 char opr;
};
int main() {
 int ans;
 struct calculator c;
 printf("\n Enter num1: ");
 scanf("%d",&c.num1);
 printf("\n Enter num2: ");
 scanf("%d",&c.num2);
 printf("\n Enter operator: ");
 scanf("%c",&c.opr);
 int calculate(int n1,int n2, char ch)
 {
 int result;
 switch(ch)
 {
 case '+': result=n1+n2;
 break;
 case '-': result=n1-n2;
 break;
 case '/': result=n1/n2;
 break;
 case '*': result=n1*n2;
 break;
 default : printf("\n\n Invalid inputs....");
 }
 return result;
 }
 printf("\n %d\t%d\t%d",c.num1,c.num2,c.opr);
 ans=calculate(c.num1,c.num2,c.opr);
 printf("\n\n Answer is = %d",ans);
return 0;
}

output1:
 Enter num1: 24
 Enter num2: 5
 Enter operator: *

 Answer is = 120

 output2:
 Enter num1:45
 Enter num2:56
 Enter operator: &

 Invalid inputs....


Passing structure by value/address to the function :
  • We can pass entire structure as an argument to the function.
  • We can pass it either by values or by address.
  • In order to pass structure by address to a function we need to pass pointer to particular structure as an argument in function definition.
  • To access members of structure pointer we need to use arrow(->) operator.
  • Let's see example :


1) Program illustrating passing structure by value :

#include<stdio.h>
typedef struct student
{
 int rno;
 char name[30];
 float perc;
};

int main()
{
 struct student s1={11,"Almas",85.3};
 void disp_data(struct student s)
 {
 printf("Your data is: \n");
 printf("\n Roll no.= %d",s.rno);
 printf("\n Name = %s",s.name);
 printf("\n Percentage= %f",s.perc);
 }
 //passing structure by value
 disp_data(s1);
 return 0;
}

Output :
Your data is:
 Roll no.= 11
 Name = Almas
 Percentage= 85.300003


2) Program illustrating passing structure by address :

#include<stdio.h>
typedef struct student
{
 int rno;
 char name[30];
 float perc;
};
int main() {
 struct student s1={11,"Almas",85.3};
 void disp_data(struct student *s)
 {
 printf("Your data is: \n");
 printf("\n Roll no.= %d",s->rno);
 printf("\n Name = %s",s->name);
 printf("\n Percentage= %f",s->perc);
 }
 //passing structure by address
 disp_data(&s1);
 return 0;
}

Output :
Your data is: 
 Roll no.= 11
 Name = Almas
 Percentage= 85.300003



Unions  :
  • Union is also a user defined data type which can store various values of different data types similar to structure. 
  • Difference between union and structure is that structure allocates separate memory to each of its member where as union uses shared memory by allocating memory equal to highest memory requirement among its members. 
  • Union keyword is used to define union. 
  • Syntax  :

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


  • For example  consider following program  :
1) Program to illustrate memory allocation of structure and union

#include<stdio.h>
union student
{
int rno;
char name[40];
float perc;
};

struct stud
{
int rno;
char name[40];
float perc;
};

int main()
{
union student s1;
struct stud s2;
//to illustrate memory allocation
printf("\n size of structure : %d bytes",sizeof(s2));
printf("\n size of union : %d bytes",sizeof(s1));
return 0;
}

Output :
size of structure : 48 bytes
size of union : 40 bytes

Note : Here union has allocated only 40 bytes to its object which is size of char name[40] since this is higher memory requirement among its members. Whereas structure has allocated separate memory to each member this total memory (4+40+4) 48 bytes is allocated.


2)Program to illustrate union :

#include<stdio.h>
#include<string.h>
union student
{
int rno;
char name[40];
float perc;
};

int main() 
{
union student s;
s.rno=56;
printf("\n Details are :\n");
printf("Roll number : %d",s.rno);
strcpy(s.name,"Amit");
printf("\n Name : %s",s.name);
s.perc=78.2;
printf("\n Percentage : %f",s.perc);
return 0;
}

Output :
Details are :
Roll number : 56
Name : Amit
Percentage : 78.199997

Note : Remember that since union is using shared memory /common memory values assigned to one member gets also initialized to other members. Thus we need to assign and display immediately.


Difference between Union and Structure:




Comments

Popular posts from this blog

Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

C program to accept names of n cities and search for city named “Pune”.