Structures
Structures
Agenda
• Introduction
• Structure Definition & Declaration
• Accessing Structure Member & Initialization
• Arrays Vs Structures
• Size of Structures
• Comparing and copying structure variables
• Slack Bytes
• Array of Structures
• Arrays Within Structures
• Nested Structures
• Structures and Functions
• References
Introducti
on
•Structures are User defined data types.
•Collection of logically related data with same or different data-type.
•The logically related data are grouped together in a common name.
•Helps to organize complex data in a more meaningful way.
•Used to represent heterogeneous data.
•A function can return a structure.
Defining a
Syntax
Structure Example
struct tag_name struct book
{ {
data-type field1; char title[20];
data-type field2; char author[15];
……… int pages;
}; float price;
};
• The keyword struct declares a structure to hold the details of four fields, namely title,
author, pages and price.
• These fields are called structure elements or members and each member belong to different
type of data.
• book is the name of the structure and is also called as ‘STRUCTURE TAG’.
Defining a
Structure
• The above declaration has not declared any variables.
• It simply describes a format called template to represent information
as below:
Array of 15 characters
author
pages integer
float
price
Declaration of structure
•
variable
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.
1) Declaring Structure variables separately 2) Declaring Structure variables with structure definition
struct student struct student
{ {
char name[25]; char name[25];
int age; int age;
char branch[10]; char branch[10];
//F for female and M for male //F for female and M for male
char gender; char gender;
}; } s1, s2;
//declaring variables of struct student Here s1 and s2 are variables of structure student.
struct student s1, s2;
Accessing Structure Members
• Structure members can be accessed and assigned values in a number of ways.
• Structure members have no meaning individually without the structure.
• In order to assign a value to any structure member, the member name must be
linked with the structure variable using a dot . operator also called period or
member access operator.
• Eg:-
book.price
is the variable representing the price of book.
• We can also use scanf() to give values to structure members through terminal.
Example Program 1
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10]; OUTPUT:
//F for female and M for male Name of Student 1: Viraaj
char gender; Age of Student 1: 18
};
int main()
{
struct Student s1; /* s1 is a variable of Student type and age is a member of Student */
s1.age = 18;
strcpy(s1.name, "Viraaj"); /* using string function to add name */
/* displaying the stored values */
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
}
Example Program 2
#include <stdio.h>
struct student printf("Enter marks: ");
{
char name[50]; scanf("%f", &s.marks);
int roll;
printf("\nDisplaying Information\n");
float marks;
printf("Name: %s\n", s.name);
};
printf("Roll: %d\n", s.roll);
int main()
printf("Marks: %.2f\n", s.marks);
{
return 0;
struct student s;
}
printf("Enter information of students:\n\n");
scanf("%s“, s.name);
scanf("%d", &s.roll);
Structure Initialization
• Like a variable of any other datatype, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
OR
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73; p1.age = 23;
Arrays Vs Structures
ARRAY STRUCTURE
Array refers to a collection consisting of elements of homogenous data type. Structure refers to a collection consisting of elements of heterogenous data type.
Array is pointer as it points to the first element of the collection. Structure is not a pointer
Array size is fixed and is basically the number of elements multiplied by the size of an
Structure size is not fixed as each element of Structure can be of different type and size.
element.
Array declaration is done simply using [] and not any keyword. Structure declaration is done with the help of “struct” keyword.
Array traversal and searching is easy and fast. Structure traversal and searching is complex and slow.
struct sruct_name{
data_type array_name[size];
data_type1 ele1; data_type2 ele2; };
Array uses subscripts or “[ ]” (square bracket) for element access Structure uses “.” (Dot operator) for element access
Array elements are stored in continuous memory locations. Structure elements may or may not be stored in a continuous memory location.
Array elements are accessed by their index number using subscripts. Structure elements are accessed by their names using dot operator.
Size of Structures
• Using the sizeof() operator we can calculate the size of the structure straight forward to pass it
as a parameter.
#include<stdio.h>
struct stud
Formula for Calculating Size of Structure : -
{
Size of Structure ‘s' = sizeof(roll) + sizeof(name) + sizeof(mark)
int roll;
= 2 + 10 + 2 = 14
char name[10];
Size depends on your computer
int marks;
};
int main()
{
int size;
struct stud s;
size = sizeof(s);
printf("nSize of Structure : %d", size);
return(0);
}
Copying and Comparing
Structure Variables
• Two variables of the same structure type can be copied the same way as ordinary
variables.
• If
e1 and e2 belong to the same type, then the following statement is valid. e1 = e2,
and e2 = e1;
• However, the statements e1 < e2; e1== e2; and e1 != e2; are not permitted.
•C language doesn't permit any logical operations on structure variables.
• We can compare two structure variables but comparison of members of a structure
can only be done individually.
Example Program 3
#include<stdio.h>
#include<conio.h>
struct class
{
int number;
char name[20];
float marks;
}; Output:
student2 and student 3 are equal.
main() 2, gita, 78.00
{
int x;
//Declaring and initializing structures of 'class' type
struct class student1 = {1, “Amay", 73.00};
struct class student2 = {2, "gita", 78.00};
struct class student3;
student3 = student2; // Copying student2 to student3
if ((student3.number = student2.number) && (student3.marks =
student2.marks))
// verifying results of copy //can compare names using strcmp()
{
printf("\n student2 and student3 are equal");
printf("%d %s %f\n", student3.number, student3.name, student3.marks);
}
else
printf("\n student2 and student3 are different");
}
Word Boundaries and Slack Bytes
• In computer with 4 bytes word boundary, the members of structure are stores left aligned on the
word boundary.
• A character data takes one byte and an integer takes 4 bytes.
• 3 bytes (Padding bytes) between them is left unoccupied. This unoccupied byte is known as
the slack byte.
Word Boundaries and Slack Bytes
• Slack byte used for speed optimization.
• It aligns bytes so that, that can be read/write from structure faster.
• It is an extra byte, sometimes placed between structure members to align the structure.
• If data is aligned properly, CPU can access the memory(structure members) efficiently and
faster.
• When we declare structure variables, each one of them may contain the slack bytes and the
values stored in such slack bytes are undefined(garbage).
• Due to this, even though the members of two variable values are equal, their structures do not
necessarily to be equal.
• Therefore C does not permit compassion of structures.
• However, we need to design our own function that can compare the individual members of
structure to decide whether the structures are equal or not.
Array of Structures
• We can also declare an array of structure variables.
• In which each element of the array will represent a structure variable.
• An array of structure is stored inside the memory in the same way as a multi- dimensional array.
• Example :
struct employee emp[5];
• Eg:-
struct student
{
int roll_no;
char name[20];
float marks;
} s[100];
Example Program 4
void ask()
#include<stdio.h> {
for(i = 0; i < 3; i++)
struct Employee {
{ printf("\nEnter %dst Employee record:\n", i+1);
char ename[10]; printf("\nEmployee name:\t");
int sal; scanf("%s", emp[i].ename);
}; printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
struct Employee emp[5]; }
int i, j; printf("\nDisplaying Employee record:\n");
for(i = 0; i < 3; i++)
void main() {
{ printf("\nEmployee name is %s", emp[i].ename);
ask(); printf("\nSlary is %d", emp[i].sal);
} }
}
Array within Structures
• C permits the use of array as a structure members.
• We can use single or multi-dimensional array of type int or float.
• Eg:-
struct marks
{
int number;
float subject[3];
} student[2];
Example Program 5
struct Student
{
for(i=0;i<3;i++)
int Roll;
{ Output :
char Name[25];
printf("\n\nEnter Marks %d : ",i+1); Enter Student Roll : 10
int Marks[3]; // array of marks
scanf("%d",&S.Marks[i]); Enter Student Name : Kumar
int Total;
S.Total = S.Total + S.Marks[i]; Enter Marks 1 : 78
float Avg;
} Enter Marks 2 : 89
};
Enter Marks 3 : 56
S.Avg = S.Total / 3;
void main()
The Details are:
{
printf(“The Details are:\n”); Roll : 10
int i;
printf("\nRoll : %d",S.Roll); Name : Kumar
struct Student S;
printf("\nName : %s",S.Name); Total : 223
printf("\n\nEnter Student Roll : ");
printf("\nTotal : %d",S.Total); Average : 74.00000
scanf("%d",&S.Roll);
printf("\nAverage : %f",S.Avg);
printf("\n\nEnter Student Name : ");
}
scanf("%s",&S.Name);
S.Total = 0;
/* Program 6 to understand arrays within structures and array of structures*/
#include<stdio.h>
for(j=0; j<4; j++)
struct student{
{
char name[20];
printf("Enter marks for subject %d : ", j+1);
int rollno;
scanf("%d", &stuarr[i].submarks[j] );
int submarks[4];
}
};
}
int main( )
for(i=0; i<3; i++)
{
{
int i, j;
printf("Data of student %d\n", i+1);
struct student stuarr[3];
printf("Name : %s, Roll number : %d\nMarks : ",
for(i=0; i<3; i++) stuarr[i].name, stuarr[i].rollno);
{ for(j=0; j<4; j++)
printf("Enter data for student %d\n", i+1); printf("%d ", stuarr[i].submarks[j] );
printf("Enter name : "); printf("\n");
scanf("%s", stuarr[i].name ); }
printf("Enter roll number : "); return 0;
scanf("%d", &stuarr[i].rollno); }
OUTPUT
Enter data for student 3
Enter data for student 1
Enter name : AJ
Enter name : John Enter roll number : 3
Enter roll number : 1 Enter marks for subject 1 : 45
Enter marks for subject 1 : 56 Enter marks for subject 2 : 67
Enter marks for subject 2 : 6 Enter marks for subject 3 : 89
Enter marks for subject 3 : 78 Enter marks for subject 4 : 45
Enter marks for subject 4 : 78
Data of student 1
Enter data for student 2 Name : John, Roll number : 1
Marks : 56 6 78 78
Enter name : Max
Enter roll number : 2 Data of student 2
Enter marks for subject 1 : 56 Name : Max, Roll number : 2
Enter marks for subject 2 : 45 Marks : 56 45 78 98
Enter marks for subject 3 : 78
Enter marks for subject 4 : 98 Data of student 3
Name : AJ, Roll number : 3
Marks : 45 67 89 45
Nested Structures
(Structures within Structures)
• Nesting of structures, is also permitted in C language.
• Nested structures means, that one structure has another structure as member variable.
• Example:
struct Student
{
char name[10]; void show(struct Student st)
int roll; {
}; printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
void show(struct Student st); }
void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}
Excercise
• Write a C Program to find Average marks and display student details using structure.
• Tip:
struct student
{
int rno;
float marks[5], avg;
char name[10];
}s[10];
THANK YOU