Lecture 3 - C Structure
Lecture 3 - C Structure
DATA
STRUCTURES
C Structure
WHAT IS STRUCTURE?
• Structures are derived data types (derived from primitive data types such as int
and float) that we use in order to define a collection of similar or different data
types under one same name.
– similar to a record
– may contain variables of many different data types—in contrast to arrays,
which contain only elements of the same data type
EXAMPLE
Suppose you want to keep track of your books in a library.
A new
data type
• Example
Good Programming
Practice
Always provide a structure tag name
when creating a structure type.
• There is no difference in the way memory is allocated or how the data members are
accessed through the variables in both cases.
DECLARING STRUCTURE VARIABLES
If number of variables
If number of variables
are not fixed, use this
are fixed, use this one.
one. It provides you
1. Inside a function: It saves your code to
the flexibility to
struct book declare a variable in
declare the structure
{ main() function.
variable many times.
char book_name[30];
char author[30];
int book_id; 2. Outside the function:
float price; struct book
}; {
char book_name[30];
int main() char author[30];
{ int book_id;
struct book b; // Here b is a variable of structure book float price;
} } b; // Here b is a variable of structure book.
MEMORY ALLOCATION
• When we declare variables of
the structure, separate memory
is allocated for each variable
int main()
• Moreover, structure name and its {
variable name should also be // Here b is a variable of structure book
different. struct book b;
}
HOW TO ACCESS DATA MEMBERS IN
STRUCTURES IN C
• There are basically two ways in order to access the data members in a
structure
– With the help of the structure member operator/ dot symbol (.)
• When the variable is normal type then go for struct to member
operator.
s1.height = 182.5 ;
s1.weight = 65;
s1.age = 20;
EXAMPLE
• Structure members cannot be initialized with declaration
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
WHY?
printf("Displaying:\n"); printf("Displaying:\n");
printf("Age: %d\n", person1.age); printf("Age: %d\n", personPtr->age);
printf("weight: %f", person1.weight); printf("weight: %f", personPtr->weight);
/*Assigning the values of each struct member here*/ /*Assigning the values of each struct member here*/
student.stu_id = 1234; student.stu_name = "Steve";
student.stu_age = 30; student.stu_id = 1234;
student.stu_age = 30;
/* Displaying the values of struct members */
printf("Student Name is: %s", student.stu_name); /* Displaying the values of struct members */
printf("\nStudent Id is: %d", student.stu_id); printf("Student Name is: %s", student.stu_name);
printf("\nStudent Age is: %d", student.stu_age); printf("\nStudent Id is: %d", student.stu_id);
return 0; printf("\nStudent Age is: %d", student.stu_age);
} return 0;
}
TYPEDEF IN C
• typedef keyword
– is used to create an alias (alternate) name for data types.
– reduces the length of the code and complexity of data types.
– helps in understanding the program.
• typedef statement does not occupy any memory; it simply defines a new type.
– typedef int INTEGER then INTEGER is the new name of data type int
– INTEGER num=5;
= =
float inch; float inch; float inch;
}; }; } DISTANCE;
#define MAX_NAME_SIZE 40
typedef struct {
char name[MAX_NAME_SIZE]; Defines a new data type
int rollno; called StudentRecord.
int midterm; Does not declare a
int final; variable.
char letterGrade;
} StudentRecord;
StudentRecord is a type;
StudentRecord s1; s1 is variables
OPERATING WITH STRUCTURE
VARIABLE However, we can perform arithmetic
operations with individual members of one
structure
we cannot
/* Invalid Operations */ • perform I/O, arithmetic
struct student
stu1 + stu2 and relational
{
stu1 - stu2 operators,
char name[20];
stu1 == stu2 • directly scanf or printf
double roll;
stu1 != stu2 etc. structs
char gender;
int marks[5]; we can
/* Valid Operation */ • copy one structure
}stu1,stu2;
stu1 = stu2 variable to another
• have a struct as a function
return type
Compare struct
variables member wise
(NOT
THE WHOLE
STRUCTURE)
NESTED STRUCTURES
• A structure that contains another
structure as its member is called a
nested structure
ID NAME
day month year
#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);
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.phone);
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);
}
ARRAY OF
#include<stdio.h>
struct student {
STRUCTURE
char name[20];
int id;
float marks;
};
void main()
Consider a case, where we need to {
struct student s1,s2,s3, s4, s5;
store the data of 5 students.
printf("Enter the name, id, and marks of student 1 ");
We can store it by using the structure scanf("%s %d %f",s1.name, &s1.id, &s1.marks);
as given right side. printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name, &s2.id, &s2.marks);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name, &s3.id, &s3.marks);
However, the complexity of the
program will be increased if there printf("Printing the details....\n");
are 200 students. printf("%s %d %f\n",s1.name, s1.id, s1.marks);
printf("%s %d %f\n",s2.name, s2.id, s2.marks);
printf("%s %d %f\n",s3.name, s3.id, s3.marks);
}
ARRAY OF STRUCTURE
• C enables us to declare an array of structures by using which, we can avoid
declaring the different structure variables;
equivalent to
new in Java
(and C++)
When we have to dynamically allocate memory for variables in our programs then
pointers are the only way to go!!.
BIG PICTURE OF A RUNNING PROGRAM’S MEMORY
0x7FFFFFFFFFFF
Unused
Read/Write Data
Loaded from the executable
Read-only Code and Data
Unused
0x000000000000
Local variables
program instructions
and the global variables
free(p)
if (ptr == NULL) {
fprintf(“Out of memory.\n”);
exit(1);
}
DYNAMIC MEMORY ALLOCATION OF
STRUCTS
#include <stdio.h> for(i = 0; i < n; ++i)
#include <stdlib.h> /* for malloc */ {
printf("Enter first name and age respectively: ");
struct person {
int age; // To access members of 1st struct person,
float weight; // ptr->name and ptr->age is used
char name[30];
}; // To access members of 2nd struct person,
// (ptr+1)->name and (ptr+1)->age is used
int main() scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);
{ }
struct person *ptr;
int i, n; printf("Displaying Information:\n");
for(i = 0; i < n; ++i)
printf("Enter the number of persons: "); printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);
scanf("%d", &n);
return 0;
// allocating memory for n numbers of struct person }
ptr = (struct person*) malloc(n * sizeof(struct person));
C STRUCTURE AND FUNCTION
• A function may access the members of a structure in three ways
#include <stdio.h>
void display(struct student s) {
struct student { printf("\nDisplaying information\n");
char name[50]; printf("Name: %s", s.name);
int age; printf("\nAge: %d", s.age);
}; }
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);
return 0;
}
STRUCTURE PADDING IN C
struct student {
char a;
char b;
int c;
} stud1;
The processor does not read 1 byte at a time. It reads 1 word at a time.
The structure occupies the contiguous block of memory as shown in the above diagram
WHY STRUCTURE PADDING?
If we consider the 32-bit architecture,
in one CPU cycle;
can be accessed.
What if we only want to access the variable 'c' We require two cycles
Lower the number of cycles, better is the performance of the CPU. This is an
unnecessary wastage of CPU cycles. Due to this reason, the structure padding
concept was introduced to save the number of CPU cycles. The structure
padding is done automatically by the compiler.
STRUCTURE PADDING IN C
• Structure padding is a concept in C that adds the one or more empty
bytes between the memory addresses to align the data in memory.
• The compiler can use padding and in that case there will be unused
space created between two data members.
– optional
• The padding is done for the alignment of data members which makes the
access to the member faster.
HOW IS STRUCTURE PADDING DONE?
After structure padding, the total memory occupied by the structure is 8 bytes.
Although the memory is wasted, the variable can be accessed within a single cycle.
#include <stdio.h>
int main()
{
struct student stud1;
return 0;
} The size of the student structure is 8
the total memory required is 12 bytes
struct student
{
char name[20];
int roll;
char gender;
int marks[5];
} stu1;
HOW TO AVOID THE STRUCTURE
PADDING IN C?
• The structural padding is an in-built process that is automatically done by the compiler.
• One way to decrease the amount of padding to a possible minimum is by declaring the
member variables in decreasing order of their size.
struct stu {
char name[20];
unsigned int age;
char gender;
float marks[5];
struct stu next; // ERROR
struct stu *next; // pointer
};