Unit-II(Structures)
ď Introduction toStructures
ď 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:
ď Iwant 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:
ď IfI 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:
structstructure 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.)
ď we startwith 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
structstudent_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:
structBooks
{
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: Structuremembers 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 variablesseparately:
ď 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 variableswith
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 ofa 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 ofa 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;
Structure pointer operator(->arrowoperator)
ď 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)
Memory Allocation forStructure
ď 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 atcompile 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
structPoint
{
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 canhave 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 atRun 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 Students;
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 displaystudent 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 displayemployee details
#include<stdio.h>
#include<string.h>
struct employee
{
char name[30];
int empId;
float salary;
};
//next page program
Limitations of CStructures
ď 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 DataHiding: 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;
};
intmain()
{
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 of2 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
ď Onestructure 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
Examples:
struct Date
{
int day;
intmonth;
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;
};
Example:By separate
structure:
struct Date
{
intday;
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 normalvariable
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;
intmonth;
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 anddisplay 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 Students;
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 anddisplay 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 Students;
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);
}
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:
ď Theembedded 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 arrayof 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 anddisplay 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 students;
ď 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;
ď };
Array of Nestedstructures
ď 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