SlideShare a Scribd company logo
MODULE 5:STRUCTURE
AND UNION
CO4:Demonstrate
the use of arrays,
strings and
structures in C
language.
CONTENTS
● Concept of Structure and Union
● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
NEED FOR STRUCTURE
Suppose, you want to store information about a person: his/her
name, citizenship number, and salary.
You can create different variables name, citNo and salary to
store this information.
What if you need to store information of more than one person?
Now, you need to create different variables for each information
per person: name1, citNo1, salary1, name2, citNo2, salary2,
etc.
A better approach would be to have a collection of all related
information under a single name Person structure and use it for
every person.
STRUCTURE
A structure is a user-defined data type available in C that allows to
combining data items of different kinds. Structures are used to
represent a record.
Defining a structure: To define a structure, you must use the struct
statement. The struct statement defines a new data type, with more
than or equal to one member. The format of the struct statement is
as follows:
struct [structure name]
{
member definition;
member definition;
...
member definition;
};
STRUCTURE
Example
struct employee
{
char name[50];
int empno;
float salary;
};
DECLARING STRUCTURE VARIABLE
You can declare structure variable in two ways:-
1. By struct keyword within main() function
2. By declaring variable at the time of defining structure.
DECLARING STRUCTURE VARIABLE
When a struct type is declared, no storage or memory is
allocated. To allocate memory of a given structure type
and work with it, we need to create variables.
struct employee
{
char name[50];
int id;
float salary;
};
int main()
{
struct employee e1, e2, e[20];
return 0;
}
DECLARING STRUCTURE VARIABLE
struct employee
{
char name[50];
int id;
float salary;
} e1, e2, e[20];
In both cases, two variables e1, e2, and an array variable e
having 20 elements of type struct employee are created.
DECLARING STRUCTURE VARIABLE
#include <stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[60];
}s1; //declaring s1 variable for structure
void main( )
{ //store first employee information
s1.rollno=1;
strcpy(s1.name, “nikhat”);//copying string into char array
//printing first employee information
printf( "Rollno : %dn", s1.rollno);
printf( "Name : %sn", s1.name);
}
ACCESS MEMBERS OF A
STRUCTURE
There are two types of operators used for accessing members of a
structure.
. Member operator
-> Structure pointer operator (to access the members of the
structure
that being referenced using pointer)
Suppose, you want to access the salary of e2 (Using member
operator)
e2.salary
To access the members of the structure referenced using the
pointer we use the operator “->”.This operator is called as arrow
operator. Using this we can access all the members of the
structure and we can further do all operations on them.
s->age=18;
KEYWORD typedef
We use the typedef keyword to create an alias name for data
types. It is commonly used with structures to simplify the
syntax of declaring variables.
struct distance
{
int feet;
float inch;
};
int main()
{
struct distance d1, d2;
}
Keyword typedef
typedef struct distance
{
int feet;
float inch;
} distance;
int main()
{
distance d1, d2;
}
NESTED STRUCTURES
C provides us the feature of nesting one structure within another
structure by using which, complex data types are created.
For example, we may need to store the address of an entity employee
in a structure. The attribute address may also have the subparts as
street number, city, state, and pin code.
Hence, to store the address of the employee, we need to store the
address of the employee into a separate structure and nest the
structure address into the structure employee.
NESTED STRUCTURES
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
NESTED STRUCTURES
void main ()
{
struct employee emp;
printf("Enter employee information?n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.a
dd.phone);
printf("Printing the employee informationn");
printf("name: %snCity: %snPincode: %dnPhone: %s",emp.name,e
mp.add.city,emp.add.pin,emp.add.phone);
}
NESTED STRUCTURES
The structure can be nested in the following ways.
1. By separate structure
2. By Embedded structure
NESTED STRUCTURES
1) Separate structure
Here, 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;
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.
NESTED STRUCTURES
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.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
ACCESSING NESTED STRUCTURE
We can access the member of the nested structure by Outer Structure
variable. Inner Structure variable .member of inner structure
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
ACCESSING NESTED STRUCTURE
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
ACCESSING NESTED STRUCTURE
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, “Nikhat");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee information
printf( "employee id : %dn", e1.id);
printf( "employee name : %sn", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%dn", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}
ARRAY OF STRUCTURES
An array of structures can be defined as the collection of
multiple structures variables 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.
To declare an array of structure, first the structure must be
defined and then an array variable of that type should be
defined.
For Example − struct book b[10]; //10 elements in an array of
structures of type ‘book’
ARRAY OF STRUCTURES
INITIALIZING ARRAY OF
STRUCTURES
struct car
{
char make[20];
char model[30];
int year;
};
struct car arrcar[2] = {
{"Audi", "TT", 2016},
{"Bentley", "Azure", 2002}
};
ARRAY OF STRUCTURES
Consider a case, where we need to store the data of 5 students.
We can store it by using the structure
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
ARRAY OF STRUCTURES
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;
}
PASSING STRUCTURE TO
FUNCTION
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void display(struct employee);
PASSING STRUCTURE TO
FUNCTION
void main ()
{
struct employee emp;
printf("Enter employee information?n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.pho
ne);
display(emp);
}
void display(struct employee emp)
{
printf("Printing the details....n");
printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
UNION
Union also stores the elements of different types i.e
heterogeneous elements. The union keyword is used to define
structure. Union takes the memory of largest member only so
occupies less memory than structures.
Structures allocate enough space to store all their members,
whereas unions can only hold one member value at a time.
We use the union keyword to define union.
union car
{
char name[50];
int price;
};
CREATE UNION VARIABLES
When a union is defined, it creates a user-defined type. However, no memory is
allocated. To allocate memory for a given union type and work with it, we need to
create variables.
1. Inside main function
union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2, *car3;
return 0;
}
CREATE UNION VARIABLES
2. During declaration
union car
{
char name[50];
int price;
} car1, car2, *car3;
In both cases, union variables car1, car2, and a union pointer
car3 of union car type are created.
ACCESS MEMBERS OF A UNION
We use the . operator to access members of a union.
To access pointer variables, we use the -> operator.
In the above example,
•To access price for car1, car1.price is used.
•To access price using car3, either (*car3).price or car3->price
can be used.
ACCESS MEMBERS OF A UNION
#include <stdio.h>
union Job
{
float salary;
int workerNo;
} j;
int main()
{
j.salary = 12.3;
// when j.workerNo is assigned a value,
// j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1fn", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
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.
DIFFERENCE BETWEEN UNIONS
AND STRUCTURES
#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;
}
DIFFERENCE BETWEEN
STRUCTURES AND UNIONS
size of union = 32
size of structure = 40
Here, the size of sJob is 40 bytes because
•the size of name[32] is 32 bytes
•the size of salary is 4 bytes
•the size of workerNo is 4 bytes
However, the size of uJob is 32 bytes. It's because the size of a
union variable will always be the size of its largest element. In
the above example, the size of its largest element, (name[32]),
is 32 bytes.
With a union, all members share the same memory.
DIFFERENCE BETWEEN
STRUCTURES AND UNIONS

More Related Content

What's hot (20)

PPTX
Handling of character strings C programming
Appili Vamsi Krishna
 
PPTX
classes and objects in C++
HalaiHansaika
 
PPT
Strings in c
vampugani
 
PPTX
Structure in C language
CGC Technical campus,Mohali
 
PPT
Structure in c
Prabhu Govind
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PPTX
This pointer
Kamal Acharya
 
PPTX
File handling in c
aakanksha s
 
PPTX
Unit 9. Structure and Unions
Ashim Lamichhane
 
PPTX
Dynamic memory allocation in c
lavanya marichamy
 
PPTX
Programming in c Arrays
janani thirupathi
 
PPT
Union In language C
Ravi Singh
 
PPTX
Control structures in c++
Nitin Jawla
 
PPTX
Structure & union
Rupesh Mishra
 
PPTX
Pointers in c language
Tanmay Modi
 
PPTX
Presentation on c structures
topu93
 
PPTX
Data types in C language
kashyap399
 
PDF
What is CPU Register? Type of CPU Register.
Kapil Dev Das
 
PPTX
Linked list
KalaivaniKS1
 
PPTX
stack & queue
manju rani
 
Handling of character strings C programming
Appili Vamsi Krishna
 
classes and objects in C++
HalaiHansaika
 
Strings in c
vampugani
 
Structure in C language
CGC Technical campus,Mohali
 
Structure in c
Prabhu Govind
 
Functions in c++
Rokonuzzaman Rony
 
This pointer
Kamal Acharya
 
File handling in c
aakanksha s
 
Unit 9. Structure and Unions
Ashim Lamichhane
 
Dynamic memory allocation in c
lavanya marichamy
 
Programming in c Arrays
janani thirupathi
 
Union In language C
Ravi Singh
 
Control structures in c++
Nitin Jawla
 
Structure & union
Rupesh Mishra
 
Pointers in c language
Tanmay Modi
 
Presentation on c structures
topu93
 
Data types in C language
kashyap399
 
What is CPU Register? Type of CPU Register.
Kapil Dev Das
 
Linked list
KalaivaniKS1
 
stack & queue
manju rani
 

Similar to Module 5-Structure and Union (20)

PDF
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
sudhakargeruganti
 
DOC
Unit 5 (1)
psaravanan1985
 
DOCX
C programming structures &amp; union
Bathshebaparimala
 
PPTX
Programming in C session 3
Prerna Sharma
 
PPT
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
Rai University
 
PPTX
STRUCTURES IN C PROGRAMMING
Gurwinderkaur45
 
PPT
Structure and union
Samsil Arefin
 
PPTX
Programming for problem solving-II(UNIT-2).pptx
prathima304
 
PPT
pointer, structure ,union and intro to file handling
Rai University
 
PPTX
Chapter 8 Structure Part 2 (1).pptx
Abhishekkumarsingh630054
 
PPT
structure.ppt
Sheik Mohideen
 
PPT
Structure c
thirumalaikumar3
 
PPT
C Language_PPS_3110003_unit 8ClassPPT.ppt
NikeshaPatel1
 
PDF
Structure and Union (Self Study).pdfStructure and Union (Self Study).pdf
monimhossain14
 
PPTX
Fundamentals of Structure in C Programming
Dr. Chandrakant Divate
 
PDF
Structure In C
yndaravind
 
PDF
Unit 3
TPLatchoumi
 
PPTX
Structures and Unions
Vijayananda Ratnam Ch
 
PPTX
Structures in C
Nimrita Koul
 
PPT
structure and union from C programming Language
AvrajeetGhosh
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
sudhakargeruganti
 
Unit 5 (1)
psaravanan1985
 
C programming structures &amp; union
Bathshebaparimala
 
Programming in C session 3
Prerna Sharma
 
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
Rai University
 
STRUCTURES IN C PROGRAMMING
Gurwinderkaur45
 
Structure and union
Samsil Arefin
 
Programming for problem solving-II(UNIT-2).pptx
prathima304
 
pointer, structure ,union and intro to file handling
Rai University
 
Chapter 8 Structure Part 2 (1).pptx
Abhishekkumarsingh630054
 
structure.ppt
Sheik Mohideen
 
Structure c
thirumalaikumar3
 
C Language_PPS_3110003_unit 8ClassPPT.ppt
NikeshaPatel1
 
Structure and Union (Self Study).pdfStructure and Union (Self Study).pdf
monimhossain14
 
Fundamentals of Structure in C Programming
Dr. Chandrakant Divate
 
Structure In C
yndaravind
 
Unit 3
TPLatchoumi
 
Structures and Unions
Vijayananda Ratnam Ch
 
Structures in C
Nimrita Koul
 
structure and union from C programming Language
AvrajeetGhosh
 
Ad

More from nikshaikh786 (20)

PPTX
Module 2_ Divide and Conquer Approach.pptx
nikshaikh786
 
PPTX
Module 1_ Introduction.pptx
nikshaikh786
 
PPTX
Module 1_ Introduction to Mobile Computing.pptx
nikshaikh786
 
PPTX
Module 2_ GSM Mobile services.pptx
nikshaikh786
 
PPTX
MODULE 4_ CLUSTERING.pptx
nikshaikh786
 
PPTX
MODULE 5 _ Mining frequent patterns and associations.pptx
nikshaikh786
 
PDF
DWM-MODULE 6.pdf
nikshaikh786
 
PDF
TCS MODULE 6.pdf
nikshaikh786
 
PPTX
Module 3_ Classification.pptx
nikshaikh786
 
PPTX
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
nikshaikh786
 
PPTX
Module 1_Data Warehousing Fundamentals.pptx
nikshaikh786
 
PPTX
Module 2_ Cyber offenses & Cybercrime.pptx
nikshaikh786
 
PPTX
Module 1- Introduction to Cybercrime.pptx
nikshaikh786
 
PPTX
MODULE 5- EDA.pptx
nikshaikh786
 
PPTX
MODULE 4-Text Analytics.pptx
nikshaikh786
 
PPTX
Module 3 - Time Series.pptx
nikshaikh786
 
PPTX
Module 2_ Regression Models..pptx
nikshaikh786
 
PPTX
MODULE 1_Introduction to Data analytics and life cycle..pptx
nikshaikh786
 
PPTX
IOE MODULE 6.pptx
nikshaikh786
 
PDF
MAD&PWA VIVA QUESTIONS.pdf
nikshaikh786
 
Module 2_ Divide and Conquer Approach.pptx
nikshaikh786
 
Module 1_ Introduction.pptx
nikshaikh786
 
Module 1_ Introduction to Mobile Computing.pptx
nikshaikh786
 
Module 2_ GSM Mobile services.pptx
nikshaikh786
 
MODULE 4_ CLUSTERING.pptx
nikshaikh786
 
MODULE 5 _ Mining frequent patterns and associations.pptx
nikshaikh786
 
DWM-MODULE 6.pdf
nikshaikh786
 
TCS MODULE 6.pdf
nikshaikh786
 
Module 3_ Classification.pptx
nikshaikh786
 
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
nikshaikh786
 
Module 1_Data Warehousing Fundamentals.pptx
nikshaikh786
 
Module 2_ Cyber offenses & Cybercrime.pptx
nikshaikh786
 
Module 1- Introduction to Cybercrime.pptx
nikshaikh786
 
MODULE 5- EDA.pptx
nikshaikh786
 
MODULE 4-Text Analytics.pptx
nikshaikh786
 
Module 3 - Time Series.pptx
nikshaikh786
 
Module 2_ Regression Models..pptx
nikshaikh786
 
MODULE 1_Introduction to Data analytics and life cycle..pptx
nikshaikh786
 
IOE MODULE 6.pptx
nikshaikh786
 
MAD&PWA VIVA QUESTIONS.pdf
nikshaikh786
 
Ad

Recently uploaded (20)

PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PPTX
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Day2 B2 Best.pptx
helenjenefa1
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 

Module 5-Structure and Union

  • 1. MODULE 5:STRUCTURE AND UNION CO4:Demonstrate the use of arrays, strings and structures in C language.
  • 2. CONTENTS ● Concept of Structure and Union ● Declaration and Initialization of structure and union ● Nested structures ● Array of Structures ● Passing structure to functions
  • 3. NEED FOR STRUCTURE Suppose, you want to store information about a person: his/her name, citizenship number, and salary. You can create different variables name, citNo and salary to store this information. What if you need to store information of more than one person? Now, you need to create different variables for each information per person: name1, citNo1, salary1, name2, citNo2, salary2, etc. A better approach would be to have a collection of all related information under a single name Person structure and use it for every person.
  • 4. STRUCTURE A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record. Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than or equal to one member. The format of the struct statement is as follows: struct [structure name] { member definition; member definition; ... member definition; };
  • 6. DECLARING STRUCTURE VARIABLE You can declare structure variable in two ways:- 1. By struct keyword within main() function 2. By declaring variable at the time of defining structure.
  • 7. DECLARING STRUCTURE VARIABLE When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables. struct employee { char name[50]; int id; float salary; }; int main() { struct employee e1, e2, e[20]; return 0; }
  • 8. DECLARING STRUCTURE VARIABLE struct employee { char name[50]; int id; float salary; } e1, e2, e[20]; In both cases, two variables e1, e2, and an array variable e having 20 elements of type struct employee are created.
  • 9. DECLARING STRUCTURE VARIABLE #include <stdio.h> #include <string.h> struct student { int rollno; char name[60]; }s1; //declaring s1 variable for structure void main( ) { //store first employee information s1.rollno=1; strcpy(s1.name, “nikhat”);//copying string into char array //printing first employee information printf( "Rollno : %dn", s1.rollno); printf( "Name : %sn", s1.name); }
  • 10. ACCESS MEMBERS OF A STRUCTURE There are two types of operators used for accessing members of a structure. . Member operator -> Structure pointer operator (to access the members of the structure that being referenced using pointer) Suppose, you want to access the salary of e2 (Using member operator) e2.salary To access the members of the structure referenced using the pointer we use the operator “->”.This operator is called as arrow operator. Using this we can access all the members of the structure and we can further do all operations on them. s->age=18;
  • 11. KEYWORD typedef We use the typedef keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables. struct distance { int feet; float inch; }; int main() { struct distance d1, d2; }
  • 12. Keyword typedef typedef struct distance { int feet; float inch; } distance; int main() { distance d1, d2; }
  • 13. NESTED STRUCTURES C provides us the feature of nesting one structure within another structure by using which, complex data types are created. For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the subparts as street number, city, state, and pin code. Hence, to store the address of the employee, we need to store the address of the employee into a separate structure and nest the structure address into the structure employee.
  • 14. NESTED STRUCTURES #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; struct employee { char name[20]; struct address add; };
  • 15. NESTED STRUCTURES void main () { struct employee emp; printf("Enter employee information?n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.a dd.phone); printf("Printing the employee informationn"); printf("name: %snCity: %snPincode: %dnPhone: %s",emp.name,e mp.add.city,emp.add.pin,emp.add.phone); }
  • 16. NESTED STRUCTURES The structure can be nested in the following ways. 1. By separate structure 2. By Embedded structure
  • 17. NESTED STRUCTURES 1) Separate structure Here, 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; 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.
  • 18. NESTED STRUCTURES 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. struct Employee { int id; char name[20]; struct Date { int dd; int mm; int yyyy; }doj;
  • 19. ACCESSING NESTED STRUCTURE We can access the member of the nested structure by Outer Structure variable. Inner Structure variable .member of inner structure e1.doj.dd e1.doj.mm e1.doj.yyyy
  • 20. ACCESSING NESTED STRUCTURE #include <stdio.h> #include <string.h> struct Employee { int id; char name[20]; struct Date { int dd; int mm; int yyyy; }doj; }e1;
  • 21. ACCESSING NESTED STRUCTURE int main( ) { //storing employee information e1.id=101; strcpy(e1.name, “Nikhat");//copying string into char array e1.doj.dd=10; e1.doj.mm=11; e1.doj.yyyy=2014; //printing first employee information printf( "employee id : %dn", e1.id); printf( "employee name : %sn", e1.name); printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%dn", e1.doj.dd,e1.doj.mm,e1.doj.yyyy); return 0; }
  • 22. ARRAY OF STRUCTURES An array of structures can be defined as the collection of multiple structures variables 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. To declare an array of structure, first the structure must be defined and then an array variable of that type should be defined. For Example − struct book b[10]; //10 elements in an array of structures of type ‘book’
  • 24. INITIALIZING ARRAY OF STRUCTURES struct car { char make[20]; char model[30]; int year; }; struct car arrcar[2] = { {"Audi", "TT", 2016}, {"Bentley", "Azure", 2002} };
  • 25. ARRAY OF STRUCTURES Consider a case, where we need to store the data of 5 students. We can store it by using the structure #include<stdio.h> #include <string.h> struct student{ int rollno; char name[10]; };
  • 26. ARRAY OF STRUCTURES 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; }
  • 27. PASSING STRUCTURE TO FUNCTION #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; struct employee { char name[20]; struct address add; }; void display(struct employee);
  • 28. PASSING STRUCTURE TO FUNCTION void main () { struct employee emp; printf("Enter employee information?n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.pho ne); display(emp); } void display(struct employee emp) { printf("Printing the details....n"); printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone); }
  • 29. UNION Union also stores the elements of different types i.e heterogeneous elements. The union keyword is used to define structure. Union takes the memory of largest member only so occupies less memory than structures. Structures allocate enough space to store all their members, whereas unions can only hold one member value at a time. We use the union keyword to define union. union car { char name[50]; int price; };
  • 30. CREATE UNION VARIABLES When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables. 1. Inside main function union car { char name[50]; int price; }; int main() { union car car1, car2, *car3; return 0; }
  • 31. CREATE UNION VARIABLES 2. During declaration union car { char name[50]; int price; } car1, car2, *car3; In both cases, union variables car1, car2, and a union pointer car3 of union car type are created.
  • 32. ACCESS MEMBERS OF A UNION We use the . operator to access members of a union. To access pointer variables, we use the -> operator. In the above example, •To access price for car1, car1.price is used. •To access price using car3, either (*car3).price or car3->price can be used.
  • 33. ACCESS MEMBERS OF A UNION #include <stdio.h> union Job { float salary; int workerNo; } j; int main() { j.salary = 12.3; // when j.workerNo is assigned a value, // j.salary will no longer hold 12.3 j.workerNo = 100; printf("Salary = %.1fn", j.salary); printf("Number of workers = %d", j.workerNo); return 0; }
  • 34. 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.
  • 35. DIFFERENCE BETWEEN UNIONS AND STRUCTURES #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; }
  • 36. DIFFERENCE BETWEEN STRUCTURES AND UNIONS size of union = 32 size of structure = 40 Here, the size of sJob is 40 bytes because •the size of name[32] is 32 bytes •the size of salary is 4 bytes •the size of workerNo is 4 bytes However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In the above example, the size of its largest element, (name[32]), is 32 bytes. With a union, all members share the same memory.