Structure and Union
Structure and Union
Introduction:
• A structure is a collection of variables of different data types under a single name.
• The variables are called members of the structure.
• The structure is also called a user-defined data type.
Defining a Structure
• Syntax:
struct structure_name
{
data_type member_variable1; data_type member_variable2;
………………………………;
data_type member_variableN; };
Once structure_name is declared as new data type, then variables of that type can be declared as:
struct structure_name structure_variable;
Note: The members of a structure do not occupy memory until they are associated with a
structure_variable
Example:
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
struct student st;
It is possible to declare variables of a structure, either along with structure definition or after the
structure is defined. Structure variable declaration is similar to the declaration of any normal
variable of any other data_type. Structure variables can be declared in following two ways:
1
1) Declaring Structure variables separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct Student
Structure initialization
Syntax:
struct structure_name structure_variable={value1, value2, … , valueN};
There is a one-to-one correspondence between the members and their initializing values.
Note: C does not allow the initialization of individual structure members within the structure
definition template.
Accessing member of structure/ Processing a structure
By using dot (.) operator or period operator or member operator.
Syntax:
structure_variable.member
Here, structure_variable refers to the name of a struct type variable and member
refers to the name of a member within the structure.
Example:
#include<stdio.h>
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long long int phone_no;
};
int main()
{
2
struct student st1={"ABC", 4, 79.5, 'M', 9848833271};
printf("Name\t\tRollNo.\t\tMarks\t\tGender\tPhoneNo.");
printf("\n \n");
printf("\n %s\t\t %d\t\t %f\t %c\t %lld", st1.name, st1.roll_no, st1.marks, st1.gender, st1.phone_no);
return 0;
}
How structure elements are stored?
The elements of a structure are always stored in contiguous memory locations.
A structure variable reserves number of bytes equal to sum of bytes needed to each of its members.
Computer stores structures using the concept of “word boundary”. In a computer with two bytes word
boundary, the structure variables are stored left aligned and consecutivelyone after the other.
Example
#include<stdio.h>
struct student
{
char name[20];
int roll;
float mark;
};
int main()
{
struct student s;
printf("Enter name:\t");
gets(s.name);
printf("\n Enter roll:\t");
scanf("%d", &s.roll);
printf("\n Enter marks:\t");
scanf("%f", &s.mark);
printf("\n Name \t Roll \t Mark\n");
printf("\n...................................\n");
printf("\n%s\t%d\t%f", s.name, s.roll, s.mark);
return 0;
}
3
Array of structure
We can also declare an array of structure variables. in which each element of the array will represent
a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is of type Employee.
#include<stdio.h>
struct employee
{
char ename[10];
int sal;
};
struct employee emp[5];
int i, j;
int main()
{
for(i = 0; i < 3; i++)
{
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
printf("The information of three employees are\n");
for(i = 0; i < 3; i++)
{
printf("\nEmployee name is %s\t",emp[i].ename);
printf("\nThe salary of employee is %d\t",emp[i].sal );
}
return 0;
}
4
Example:
#include <stdio.h>
struct student
{
char name[20];
int roll_no;
char course[20];
float marks_obtained;
char grade[2];
};
int main()
{
struct student stud[20];
int i;
printf("Enter the student data one by one\n");
for(i=0;i<5;i++)
{
printf("Enter the roll number of %d student",i+1);
scanf("%d",&stud[i].roll_no);
printf("Enter the name of %d student\n",i+1);
scanf("%s",stud[i].name);
printf("Enter the course of %d student\n",i+1);
scanf("%s",&stud[i].course);
printf("Enter the marks obtained of %d student\n",i+1);
scanf("%f",&stud[i].marks_obtained);
printf("Enter the grade of %d student\n",i+1);
scanf("%s",&stud[i].grade);
}
printf("======The data entered for students are======");
for(i=0;i<5;i++)
{
printf("The roll number is %d\n",stud[i].roll_no);
printf("The name of %d student is %s\n",i+1,stud[i].name);
printf("The course of %d student is %s\n",i+1,stud[i].course);
printf("The marks obtained by %d student is %.2f\n",i+1,stud[i].marks_obtained);
printf("The grade obtained by %d student is %s\n",i+1,stud[i].grade);
}
return 0;
}
5
Nesting of structure: Defining the structure variable within another structure definition (declaration) is
called nested structure. The following code segments illustrate the nested structure.
struct time
{
int hrs;
int mins;
};
struct date
{
int day;
int month;
int year;
};
struct flightschedule
{
int flightno;
struct time departuretime;
struct time arrivaltime;
struct date scheduledate;
};
Here the structure variables departuretime, arrivaltime and scheduletime are members of the structure
flightschedule. These are said to be nested within the structure flightschedule. The declaration of time
and date must precede the declaration of flightschedule.
Accessing Nested structure members
Suppose, we declare a structure variable named myflight of type flightschedule as shown
struct flightschedule myflight;
To access the hrs of departuretime member of myflight, we must apply the dot operator twice. For
example, the following statement assigns 9 hrs of departuretime
myflight.departuretimr.hrs=9;
Example:
#include<stdio.h>
int main()
{
struct time
{
int hrs;
int mins;
};
struct date
{
int day;
char month[20];
int year;
};
struct flightschedule
{
int flightno;
struct time departuretime;
6
struct time arrivaltime;
struct date scheduledate;
};
struct flightschedule myflight;
printf("Enter the departure time in hours");
scanf("%d", &myflight.departuretime.hrs);
printf("Enter the departure time in minutes");
scanf("%d", &myflight.departuretime.mins);
printf("Enter the arrival time in hours");
scanf("%d", &myflight.arrivaltime);
printf("Enter the day of flight");
scanf("%d", &myflight.scheduledate.day);
printf("Enter the month of flight");
scanf("%s", myflight.scheduledate.month);
printf("Enter the year of flight");
scanf("%d", &myflight.scheduledate.year);
printf("The detail information of flight is\n");
printf("The flight time is %d : %d O-clock\n",myflight.departuretime.hrs,myflight.departuretime.mins
);
printf("The arrival time is %d O-clock\n", myflight.arrivaltime);
printf("The day of arrival of flight is %d th of %s %d",
myflight.scheduledate.day,myflight.scheduledate.month, myflight.scheduledate.year);
return 0;
}
Example:
#include<stdio.h>
/* Declaration of structure */
struct address
{
int houseno;
char street[20];
int stateno;
};
/* Declaration of structure */
struct student
{
char name[30];
int roll;
struct address adrs; /* Nested structure */
};
int main()
{
struct student stud;
printf("Enter name and roll number of student:\n");
scanf("%s%d",stud.name, &stud.roll);
printf("Enter street name, house number and state number:\n");
scanf("%s%d%d",stud.adrs.street, &stud.adrs.houseno, &stud.adrs.stateno);
7
printf("Student detail is:\n");
printf("Name: %s\tRoll: %d\n", stud.name, stud.roll);
printf("Address:%s, House no. %d, state: %d",stud.adrs.street, stud.adrs.houseno, stud.adrs.stateno);
return 0;
}
Example:
#include<stdio.h>
struct person
{
char name[20];
int age;
char dob[10];
};
struct student
{
struct person info;
int roll_no;
float marks;
};
int main()
{
struct student s1;
printf("Details of student: \n\n");
printf("Enter name: ");
scanf("%s", s1.info.name);
printf("Enter age: ");
scanf("%d", &s1.info.age);
printf("Enter dob: ");
scanf("%s", s1.info.dob);
printf("Enter roll no: ");
scanf("%d", &s1.roll_no);
printf("Enter marks: ");
scanf("%f", &s1.marks);
printf("\n*******************************\n\n");
printf("Name: %s\n", s1.info.name);
printf("Age: %d\n", s1.info.age);
printf("DOB: %s\n", s1.info.dob);
printf("Roll no: %d\n", s1.roll_no);
printf("Marks: %.2f\n", s1.marks);
return 0;
}
8
Pointer of structure variable:
struct book
{
char name [20];
int pages;
float price;
};
struct book *bptr;
However, this declaration for a pointer to structure does not allocate any memory for a structure but
allocates only for a pointer, so that to access structure’s members through pointer bptr.
Now, individual structure members are accessed as:
bptr->name bptr->pages bptr->price
or
(*bptr).name (*bptr).pages (*bptr).price
Here, -> is called arrow operator and there must be a pointer to the structure on the left side of t
Also, the address of a structure type variable can be stored in a structure type pointer variable as
struct book
{
char name[20];
int pages;
float price;
};
struct book b, *bptr;
bptr=&b;
• Here, the base address of b is assigned to bptr pointer.
• Now the members of the structure book can be accessed in 3 ways as:
9
Example:
// Program to illustrate pointer of structure variable.
#include <stdio.h>
struct student
{
int rollno;
char name[20]; float per;
};
int main()
{
struct student stu,*p;
p= &stu;
printf("Enter the roll number");
scanf("%d", &p->rollno);
printf("Enter the name of student");
scanf("%s", p->name);
printf("Enter the percentage of student");
scanf("%f", &p->per);
printf(" The information about the student is \n");
printf("Roll number=%d\n",(*p).rollno);
printf("Name of student is =%s\n",(*p).name);
printf("Percentage of student =%f\n", (*p).per);
return 0;
}
Alternatively we can do the same program as
#include <stdio.h>
struct student
{
int rollno;
char name[20];
float per;
};
int main()
{
struct student stu,*ptr;
ptr= &stu;
printf("Enter the roll number");
scanf("%d", &stu.rollno);
printf("Enter the name of student");
scanf("%s", stu.name);
printf("Enter the percentage of student");
scanf("%f", &stu.per);
printf(" The information about the student is \n");
printf("Roll number=%d\n",ptr->rollno);
printf("Name of student is =%s\n",ptr->name);
printf("Percentage of student =%f\n", ptr->per);
return 0;
}
10
Structure to pointer variable: C allows pointers to structures just as it allows pointers to any variable.
Like other pointers, structure pointers are declared by placing * in front of the structure variables name.
For example,
struct bankaccount *pAcc;
Declares pAcc as pointer to a structure variable of type struct bankaccount
Using Structure Pointers: To initialize a structure pointer, use the & operator to get the address of a
structure variable.
struct bankaccount acc, *pAcc;
pAcc = &acc;
Now pAcc is pointer to a structure of type bankaccount, and *pAcc is pointed structure variable (acc).
Example:
#include <stdio.h>
struct student
{
int rollno;
char name[20];
float per;
};
int main()
{
struct student stu,*p;
p= &stu;
printf("Enter the roll number");
scanf("%d", &p->rollno);
printf("Enter the name of student");
scanf("%s", p->name);
printf("Enter the percentage of student");
scanf("%f", &p->per);
printf(" The information about the student is \n");
printf("Roll number=%d\n",(*p).rollno);
printf("Name of student is =%s\n",(*p).name);
printf("Percentage of student =%f\n", (*p).per);
return 0;
}
Union:
A union is a special data type available in C that allows storing different data types in
the same memory location. You can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of using
the same memory location for multiple purposes.
Defining a Union: To define a union, we must use the union statement in the same
11
way as it is done while defining a structure. The union statement defines a new data
typewith more than one member for your program. The format of the union statement is
as follows:
union union_name
{
member definition;
member definition;
member definition;
........
member definition;
};
Example:
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
12
Similarities between Structure and Union
1. Both are user-defined data types used to store data of different types as a single
unit.
2. Their members can be objects of any type, including other structures and unions or
arrays. A member can also consist of a bit field.
3. Both structures and unions support only assignment = and sizeof operators. The
two structures or unions in the assignment must have the same members and
member types.
4. A structure or a union can be passed by value to functions and returned by value
by functions. The argument must have the same type as the function parameter. A
structure or union is passed by value just like a scalar variable as a corresponding
parameter.
5. ‘.’ operator is used for accessing members.
Differences
13