2. Unit-II(Structures)
Introduction to Structures
Definition
Initialization of Structures
Accessing structure members
Nested Structures
Array of Structures
Structures and Functions
Unions
Typedef
Enumerated Data types.
3. Introduction to Structures:
Definition :Structure is a collection of
heterogeneous data elements.
Structure is a user-defined datatype in C
language which allows us to combine data of
different data types.
structures we can combine various data types to
store a specific type of data.
Structures are used to represent a record
Structure helps to construct a complex data type
which is more meaningful.
4. Example 1:
I want to keep track of your books in a library.
You might want to track the following attributes
about each book −
Title
Author
Subject
cast
5. Example 2:
If I want to write a program to store Student
information.
Student's name
age
branch
permanent address
father's name ….etc
which included different data types( string
values, integer values etc).
In structure, data is stored in form of records.
6. Defining a Structure
To define a structure, you must use
the struct statement.
The struct statement defines a new data type, with
more than one member.
Syntax:
struct structure_name(or)structure tag
{
//member variable 1 ;
//member variable 2;
//member variable 3;
...
};
7. Defining a Structure
Syntax:
struct structure tag(or)structure name
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional .
Each member definition is a normal variable definition,
(int i; or float f; or any other valid variable definition.)
9. we start with the struct keyword.
we have to mention all the member variables,
which are nothing but normal C language
variables of different types like int, float, array
etc.
Note: The closing curly brace in the structure
type declaration must be followed by a
semicolon(;).
10. Example of Structure
struct student_name
{
char studentname[20];
int age;
char branch[20] ;
char gender[10];
};
Here,
struct Student name declares a structure to hold the details of a
studentdetails .
which consists of 4 data fields,
namely name, age, branch and gender.
These fields are called structure elements or members of
structures.
11. Example of Structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
book is the name of the structure and is called as
the structure tag.
12. Note: Structure members cannot be initialized
during structure definition time.
Structure name is new data type name…not a
variable
int a=10
13. Declaring Structure Variables
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 datatype.
Structure variables can be declared in following two
ways:
1. Declaring Structure variables separately
2. Declaring Structure variables along with structure
definition
14. Declaring Structure variables separately:
Syntax:
struct structurename var1,var2…;
struct Student
{
int rollno;
char name[25];
float percentage;
};
struct Student s1, s2;
//declaring variables of struct Student
the above statement can be used in any function in a program
//s1 , s2 will local variables in the function
15. Declaring Structure variables with
structure definition
struct Student
{
int rollno;
char name[25];
float percentage;
}s1,s2;
//s1 and s2 are global variables
Here ,S1 and S2 are variables of structure Student.
However this approach is not much recommended.
16. Access members of a structure
There are two types of operators used for
accessing members of a structure.
1. (.) Member operator(dot operator)
2. (-> ) Structure pointer operator(arrow
operator)
Ex:
you want to access the salary of person2. Here's
how you can do it.
person2.salary
17. Access members of a structure
(.) Member operator(dot operator):
This operator can be used to access structure
members with structure variables..
Syntax:
structurevariable. structuremember;
struct student s;
Ex:
s.rollno;
s.name;
s.percentage;
20. Structure pointer operator(->arrow operator)
This operator can be used to access structure
members with structure pointer variables.
Syntax:
structure pointervariable-
>structuremember;
struct student *p; //memory should create for
pointer variables using malloc
p=(struct student *)malloc(sizeof(struct
student));
21. Ex: p->rollno, p->name, p->percentage
s.rollno,s.name,s.perc
Structure members can be accessed and assigned
values in a number of ways.
Structure members have no meaning individually
without the structure variables.
Rollno,name,percentage --- no meaning(normal
variable)
s.rollno ,s.name, s.percentage -> meaning (str
member (variables)
p->rollno, p->name, p->percentage -
>meaning(pointer variable)
24. Memory Allocation for Structure
Memory can be allocated for structure variable
not for structure definition
When we create a structure variable, then
compiler allocate contiguous memory for the
data members of the structure.
The size of allocated memory is the sum of sizes
of all structure members.
The data members of structure is accessed with
the help of the structure variable and structure
member name.
25. struct Student
{
int rollno; 2bytes
char name[25];25 bytes
float percentage; 4bytes
Int mobile;2bytes
};
Struct student s,s1;
Note: Memory can not be created for student.
Memory can be created for structure student variable
s. rollno– 2 bytes, name- 25bytes , percentage – 4
bytes so total memory allocated for s is
31bytes(2+25+4).
26. Structure Initialization at compile time
structure variable can also be initialized at compile time.
Same like avariable (a=4)
struct Student
{
int rollno;
char name[25];
float percentage; int a[10]={1,2,3,3};
};
struct Student s={18,“sita”,93.23};//initialization structure u have to
follow order of definition
struct Student s;
s.rollno=18;//initialization of each member separately no need to
follow order.
s.percentage = 93.23;
s.name=“sita”;
27. access structure elements
struct Point
{
int x, y,z;
};
int main()
{
struct Point p1 = {0, 1};
int z;
// Accessing members of point p1
z= p1.x +p1.y;
printf ("x = %d, y = %d", p1.x, p1.y);
Printf(“z=%d”,z);
return 0;
}
Output: x = 0 y=1
Z=1
28. Initialization:
struct Point
{
int x, y, z;
};
int main()
{
// Examples of initialization using designated initialization
struct Point p1 = {.y = 0, .z = 1, .x = 2};
struct Point p2 = {.x = 20};
printf ("x = %d, y = %d, z = %dn", p1.x, p1.y, p1.z);
printf ("x = %d", p2.x);
return 0;
}
Output: x = 2, y = 0, z = 1
x = 20
29. structure pointer
we can have pointer to a structure. If we have a pointer to structure,
members are accessed using arrow ( -> ) operator.
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {1, 2};
// p2 is a pointer to structure p1
struct Point *p2 = &p1;
// Accessing structure members using structure pointer
printf("%d %d", p2->x, p2->y);
return 0;
}
Output:1 2
30. Structure Initialization at Run time
//Read and display student details
#include<stdio.h>
#include<string.h>
struct Student
{
int rollno;
char name[25];
float percentage;
};
31. void main()
{
struct Student s;
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&s.rollno);
__fpurge(stdin);// The function fpurge() clears the
buffers of the given stream
gets(s.name);
scanf(“%f”,&s.percentage);
printf("Rollno of Student : %dn", s.rollno);
printf("Name of Student : %sn", s.name);
printf("percentage of student : %fn", s.percentage);
}
32. //Read and display student details using structure pointer
#include<stdio.h>
#include<string.h>
struct Student
{
int rollno;
char name[25];
float percentage;
};
void main()
{
struct Student *p;
p=(struct student *)malloc(sizeof(struct student));
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&p->rollno);
gets(p->name);
scanf(“%f”,&p->percentage);
printf("Rollno of Student : %dn", p->rollno);
printf("Name of Student : %sn", p->name);
printf("percentage of student : %fn", p->percentage);
}
33. Read and display employee details
#include<stdio.h>
#include<string.h>
struct employee
{
char name[30];
int empId;
float salary;
};
//next page program
35. Limitations of C Structures
In C language, Structures provide a method
for packing together data of different types.
A Structure is a helpful tool to handle a group
of logically related data items. However, C
structures have some limitations.
The C structure does not allow the struct data
type to be treated like built-in data types:
We cannot use operators like +,- etc. on
Structure variables. For example, consider
the following code:
36. No Data Hiding: C Structures do not permit data
hiding. Structure members can be accessed by
any function, anywhere in the scope of the
Structure.
Functions inside Structure: C structures do not
permit functions inside Structure
Static Members: C Structures cannot have static
members inside their body
Access Modifiers: C Programming language do
not support access modifiers. So they cannot be
used in C Structures.
Construction creation in Structure: Structures
in C cannot have constructor inside Structures
37. struct number
{
float x;
};
int main()
{
struct number n1,n2,n3;
n1.x=4;
n2.x=3;
n3=n1+n2;
return 0;
}
/*Output:
prog.c: In function 'main':
prog.c:10:7: error:
invalid operands to binary + (have 'struct number' and 'struct number')
n3=n1+n2;
*/
38. Programs
1. Addition of 2 complex numbers using
structures
2. Multiplication of 2 complex numbers using
structures
3. C Program to Store Information of a Student
Using Structure
4. Program to add two distances in the inch-
feet system
39. Nested Structures
One structure variable can be declared inside
other structure as a structure member.
Nested structure in C is nothing but structure
within structure.
The structure variables can be a normal
structure variable or a pointer variable to access
the data.
When a structure contains another structure, it
is called nested structure.
1. Structure within structure in C using normal
variable
2. Structure within structure in C using pointer
41. Examples:
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date d;
float percentage;
};
struct student
{
int rollno;
char name[20];
struct Date
{
int day;
int month;
int year;
}d;
float percentage;
};
43. Example:By separate
structure:
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date *d;//member
vari
float percentage;
};
Ex:Embedded structure:
struct student
{
int rollno;
char name[20];
struct Date
{
int day;
int month;
int year;
}*d;
float percentage;
};
44. d is normal variable
s.rollno , s.name, s.d.day, s.d. month,s.d.year,
s.percentagae
d is pointer
s.rollno, s.name, s.d->day, s.d->month, s.d->year,
s.percentage
45. #include<stdio.h>
#include<string.h>
struct date
{
int day;
int month;
int year;
}d;
struct student_details
{ char name[20];
int id;
struct date d;//member variable of data str
};
int main()
{
struct student_details s;// s is a str variable declaration
printf("enter studendetail namen");
scanf("%s",s.name);
printf("enter idn");
scanf("%d",&s.id);
printf("enter date");
scanf("%d",&s.d.day);//nested
printf("enter monthn");
46. To read and display student structure details using nested structure as structure
variable
Hint: Use date of birth for nested structure.(
#include<stdio.h>
#include<string.h>
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date d;
float percentage;
};
//next slide program
47. void main()
{
struct Student s;
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&s.rollno );
gets(s.name);
scanf(“%f”,&s.percentage);
printf(“Enter Date of birth day,month and yearn”);
scanf(“%d%d%d”,&s.d.day,&s.d.month,&s.d.year);
printf("Rollno of Student : %dn", s.rollno);
printf("Name of Student : %sn", s.name);
printf(“DOB : %d-%d-%d”,s.d.day,s.d.month,s.d.year);
printf("percentage of student : %fn", s.percentage);
}
48. To read and display student structure details using nested structure as
structure pointer variable
Hint: Use date of birth for nested structure.(By separate structure:)
)
#include<stdio.h>
#include<string.h>
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date *d;
float percentage;
};
49. void main()
{
struct Student s;
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&s.rollno );
gets(s.name);
scanf(“%f”,&s.percentage);
printf(“Enter Date of birth day,month and yearn”);
scanf(“%d%d%d”,&s.d->day,&s.d->month,&s.d->year);
printf("Rollno of Student : %dn", s.rollno);
printf("Name of Student : %sn", s.name);
printf(“DOB : %d-%d-%d”,s.d->day,s.d->month,s.d->year);
printf("percentage of student : %fn", s.percentage);
}
51. Nested Structures :
TWO TYPES :
By separate structure:
By Embedded structure:.
1. By separate structure: we create two structures, but the dependent structure
should be used inside the main structure as a member. Consider the following
example.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
above example, doj (date of joining) is the variable of type Date. Here doj is used as a
member in Employee structure. In this way, we can use Date structure in many
structures.
52. 2.Embedded structure:
The embedded structure enables us to declare the structure
inside the structure. Hence, it requires less line of codes but
it can not be used in multiple data structures. Consider the
following example.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
53. An array of structures in C can be defined as the
collection of multiple structures of same where
each variable contains information about
different entities.
The array of structures in C are used to store
information about multiple entities of different
data types.
The array of structures is also known as the
collection of structures
Array of structures
55. Index—0 Emp[0].id, emp[0].name,
emp[0].salary
Index -- 1 Emp[1].id, emp[1].name,
emp[1].salary
Index --iEmp[i].id, emp[i].name, emp[i].salary
56. Ex1:array of structures
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("nEnter Name:");
scanf("%s",&st[i].name);
}
printf("nStudent Information List:");
for(i=0;i<5;i++){
printf("nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
57. // Read and display all employee details in organization
#include<stdio.h>
#include<string.h>
struct employee
{
int id,salary;
char name[20],desg[20];
};
void main()
{
int i,n;
struct employee emp[10];
printf("Enter the no of employeesn");
scanf("%d",&n);
printf("Enter employee details n");
for(i=0;i<n;i++)
{
printf("Enter employee details as id , name , designation , salaryn");
scanf("%d%s%s%d",&emp[i].id, emp[i].name, &emp[i].desg,
&emp[i].salary);
}
printf("Enter employee details aren");
for(i=0;i<n;i++)
{
printf("id:%d,name:%s,designation:%s,salary:%dn",&emp[i].id,
58. Arrays within structure
arrays may be the member within structure, this is
known as arrays within structure. Accessing arrays
within structure is similar to accessing other members.
struct student
{
int rollno;
char name[20];
intmarks[5]; //array as a member of structure
float percentage;
};
59.
Struct student s;
s.rollno, s.name, s.percentage
If s is a variable of type struct student then:
s.marks[0] – refers to the marks in the first subject
s.marks[1] – refers to the marks in the second subject
s.marks[2], s.marks[3], s.marks[4]
if index I for marks marks[i] --- s.marks[i]
60. Array within structure
struct student
{
char name[20];
int rollno;
int marks[5];
float percentage;
};
62. Array of Nested structures
struct Date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct Date d;
float percentage;
};
63. void main()
{
struct Student s[10];
int i,n;
printf(“Enter no of studentsn”);
scanf(“%d”,&n);
printf(“Enter detailsn”);
for(i=0;i<n;i++)
{
printf(“Enter rollno, name and percentagen”);
scanf(“%d”,&s[i].rollno );
gets(s[i].name);
scanf(“%f”,&s[i].percentage);
printf(“Enter Date of birth day,month and yearn”);
scanf(“%d%d%d”,&s[i].d.day,&s[i].d.month,&s[i].d.year);
}
for(i=0;i<n;i++)
{
printf("Rollno of Student : %dn", s[i].rollno);
printf("Name of Student : %sn", s[i].name);
printf(“DOB : %d-%d-%d”,s[i].d.day,s[i].d.month,s[i].d.year);
printf("percentage of student : %fn", s[i].percentage);
}
}
64. Self-Referential structures
Self- Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.
Note: Structure member may be pointer variable of same structure but not Normal
variable.
Ex1:
struct node
{
int data;
struct node*next;
};
node is self-referential structure
Ex2:
struct student
{
int rollno;
char name[20];
float percentage;
struct student *p;
};
Student is self-referential structure