Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 1
MODULE 4: Structures
STRUCTURES IN C:
Arrays are used to store large set of data and manipulate them but the disadvantage is that all
the elements stored in an array are to be of the same data type. If we need to use a collection of
different data type items it is not possible using an array.
When we require collection of data items of different data types, we can use a structure.
Structure is a method of packing data of different types. In general, structure is a collection of
data items of different data types. A Structure contains many elements each of same or
different data type.
A structure is a variable in which different types of data can be stored together with one
variable name. Consider the data a teacher might need for a student: Name, Class, GPA, test
scores, final score, etc. A structure data type called student can hold all this information
The above is a declaration of a data type called student. It is not a variable declaration, but a
type (template) declaration.
To actually declare a structure variable, the standard syntax is used:
struct student amar, Krishna, suma;
Structure members can be initialized at declaration. This is similar to the initialization of
arrays; the initial values are simply listed inside a pair of braces, with each value separated by
a comma.
What data type are allowed to structure members? Anything goes: basic types, arrays, strings,
pointers, even other structures. You can even make an array of structures.
General format of structure declaration in C:
struct tag_name // structure type (template) delcaration
{
data type member1; // elements of the structure
data type member2;
…
…
}; // semicolon required at the end of declaration
The closing bracket of structure type declaration must be followed by a semicolon. Usually
structure declaration appears at the top of the source code (before main).
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 2
Example:
struct lib_books
{
char title[20];
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. The element of the structure are known members of the structure. Each
member may belong to different or same data type. The structure we just declared is not a
variable by itself but a template for the strcture.
Note: The members of a structure do not occupy memory until they are associated with a
structure variable. We can declare structure variables using the tag name anywhere in the
program. For example, the statement
struct lib_books book1, book2, book3;
declares book1,book2,book3 as variables of type struct lib_books. Each declaration, i.e, each
variable book1, book2, book3 consists of four members of the structure lib_books.
Memory Map of structure variable book1 is as shown. Each member of the structure is
allocated memory according to its type (int, char etc) and total memory allocated to variable
book1 is the “sum” of memory allocated to all its members.
book1.title book1.author book1.pages book1.price
book1
The complete structure declaration might look like this:
struct lib_books
{
char title[20]; // title, author etc are members of the structure
char author[15];
int pages;
float price;
}; // create a structure template with members
void main ( )
{
struct lib_books, book1, book2, book3; // create 3 structure type variables
….
}
We can also combine both template declaration and variables declaration in one statement as
shown here:
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 3
struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3; // declare a structure template and create 3 variables
where, book1,book2,book3 are structure variables representing 3 books but does not include
a tag name for use in the declaration.
A structure is usually defined before main along with macro definitions. In such cases, the
structure assumes global status and all the functions can access the structure.
4.1 Accessing & initializing Structure Members:
The link between a structure member and a structure variable is established using the
member access operator ‘.’ which is known as dot operator and is used to access individual
structure element.
For example, we can access the member ‘price’ belonging to structure variable book1 as
book1. price.
 The assignment (=) operator can be used to give values to structure members.
book1.pages=250;
book1.price=28.50;
 We can also use scanf statement to assign values like
scanf(“%s”, book1.file);
scanf(“%d”, &book1.pages);
Consider another example:
struct student {
int id;
char name[10];
float avg ;
} a , b , c;
Here, we create a structure named “student” and define 3 variables a, b, c of type “student”.
The items id, name, avg are known as structure members.
a.id - refers to the member named “id” of the structure variable a.
scanf( “%d”, &a.id); this statement can accept an integer roll number of structure “a” from user.
e.g. struct book {
char name;
int pages;
float price;
}; // structure declaration
We can declare a structure variable (say z) and initialize as:
struct book z = { ‘s’, 125, 90.0};
Here, z.name is ‘s’. z.pages is 125 and z.price is 90.0
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 4
/* Example program using structures */
#include<stdio.h>
struct student
{
int id_no;
char name[20];
char address[20];
int age;
} s1;
void main( )
{
printf("Enter the student information");
printf("Now Enter the student id_no");
scanf("%d", &s1.id_no);
printf("Enter the name of the student");
scanf("%s", s1.name);
printf("Enter the address of the student");
scanf("%s", &s1.address);
printf("Enter the age of the student");
scanf("%d", &s1.age);
printf("Student informationn");
printf("student id_number=%dn", s1.id_no);
printf("student name=%sn", s1.name);
printf("student Address=%sn", s1.address);
printf("Age of student=%dn", s1.age);
}
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 5
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 6
4.2 Array of Structures:
It is possible to define an array of structures. For example, if we are maintaining information of
all the students in the college and if 100 students are studying in the college, then we need to
use an array than single structure variables. We can define an array of structures as shown in
the following example:
struct
{
int id_no;
char name[20];
char address[20];
int age;
}
student[100];
An array of structures can be assigned initial values just as any other array. Remember that
each element is a structure that must be assigned corresponding initial values as illustrated
below.
#include<stdio.h>
struct student // structure type declaration
{
int id_no; // 4 data members in the structure
char name[20];
char address[20];
int age;
}stu[100]; // create 100 variables of structure student
// i.e., array of structures just like array of 100 integers
void main( )
{
int k, n;
printf("Enter the number of students");
scanf("%d",&n);
printf(" Enter Id_no,name address & age of students n");
for(k=0;k<n; k++)
scanf ("%d %s %s %d", &stu[k].id_no, stu[k].name, stu [k].address, &stu[k].age);
printf("n Student information details are: ");
for (k=0;k< n;k++)
printf("%d %s %s %d n", stu[k].id_no, stu[k].name, stu [k].address, stu[k].age);
} // end of main
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 7
4.3 Structure within a structure (Nested Structures)
A structure may be defined as a member of another structure. In such contexts, the declaration
of the embedded structure must appear before the declarations of other structures.
Ex:
struct date
{
int day;
int month;
int year;
};
struct student
{
int id_no;
char name[20];
char address[20];
int age;
struct date doa; // “date” is a structure defined earlier
struct date dob;
} oldstudent, newstudent;
the structure student contains another structure date as its one of its members.
As mentioned earlier, structures can have other structures as members. Say you wanted to
make a structure that contained both date and time information. One way to accomplish this
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 8
would be to combine two separate structures; one for the date and one for the time. For
example,
struct date {
int month;
int day;
int year; };
struct time {
int hour;
int min;
int sec; };
struct new_date {
struct date today;
struct time now; };
• here, “new_date” a structure whose elements (members) are nothing but two other
previously declared structures.
4.4. Structures as Function Arguments:
We can pass structures as arguments to functions. Unlike array names however, which always
point to the start of the array, structure names are not pointers. As a result, when we change
structure parameter inside a function, we don’t effect its corresponding argument. i.e., the
structure is “passed by value”; so, actual arguments in the calling function are not modified.
a) Passing structure elements to functions:
A structure may be passed into a function as individual member or a separate variable.
A program example to display the contents of a structure passing the individual elements to a
function is shown below.
#include<stdio.h>
struct emp // structure declaration
{
int emp_id; // structure members
char name[25];
char department[10];
float salary;
};
void display(int, char [ ]); // function declaration
void main( )
{
static struct emp emp1={125,"RAMESH", "ECE", 50000.00};
display(emp1.emp_id, emp1.name); // function call with two members of the structure
// passed to function as individual variables
} // end of main
/* function to display structure member values */
void display(int e_no, char e_name[ ])
{
printf("%d %s", e_no, e_name);
}
Programming in C & Data Structures 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 9
b) Passing entire structure as argument to a function
#include<stdio.h>
struct dob // structure declaration
{
short int dd, mm, yy; // structure members
};
void display (struct dob d) ;// function declaration with structure as argument
void main( )
{
struct dob d1; // creating structure variable d1 of type dob
printf (“n enter your date of birth as date, month & year n”);
scanf (“%d %d %d” , &d1.dd, &d1.mm, &d1.yy);
display(d1); // function call with structure as argument
} // end of main
/* function to display structure member values */
void display(struct date x)
{
printf (" Your date of birth is : n”);
printf (“%d - %d - %d", x.dd, x.mm. x.yy);
}
4.5 Pointers to Structures:
One can have pointer variable that contain the address of complete structures, just like with
the basic data types. Structure pointers are declared and used in the same manner as “simple”
pointers.
In C, there is a special symbol -> which is used as a shorthand when working with pointers to
structures. It is officially called the structure pointer operator (arrow operator). Its syntax is
struct_ptr->member
Note:
*(struct_ptr).member is same as struct_ptr->member
Ex:
struct student {
int id;
char *name;
} stu1, stu2 ; // create 2 variables stu1 and stu2 of type struct student
void main ( )
{
struct student *stp; // stp is a pointer variable
stp = &stu1; // stp holds the address of stu1 i.e., stp “points” to stu1
// initializing structure members using pointer variable and dot operator
(*stp).id=38; // same as stu1.id = 38;
(*stp).name="Ramya";
• Thus, the last two lines of this example could also have been written as:
stp->id=38;
stp->name="Ramya";

Lk module4 structures

  • 1.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 1 MODULE 4: Structures STRUCTURES IN C: Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require collection of data items of different data types, we can use a structure. Structure is a method of packing data of different types. In general, structure is a collection of data items of different data types. A Structure contains many elements each of same or different data type. A structure is a variable in which different types of data can be stored together with one variable name. Consider the data a teacher might need for a student: Name, Class, GPA, test scores, final score, etc. A structure data type called student can hold all this information The above is a declaration of a data type called student. It is not a variable declaration, but a type (template) declaration. To actually declare a structure variable, the standard syntax is used: struct student amar, Krishna, suma; Structure members can be initialized at declaration. This is similar to the initialization of arrays; the initial values are simply listed inside a pair of braces, with each value separated by a comma. What data type are allowed to structure members? Anything goes: basic types, arrays, strings, pointers, even other structures. You can even make an array of structures. General format of structure declaration in C: struct tag_name // structure type (template) delcaration { data type member1; // elements of the structure data type member2; … … }; // semicolon required at the end of declaration The closing bracket of structure type declaration must be followed by a semicolon. Usually structure declaration appears at the top of the source code (before main).
  • 2.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 2 Example: struct lib_books { char title[20]; 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. The element of the structure are known members of the structure. Each member may belong to different or same data type. The structure we just declared is not a variable by itself but a template for the strcture. Note: The members of a structure do not occupy memory until they are associated with a structure variable. We can declare structure variables using the tag name anywhere in the program. For example, the statement struct lib_books book1, book2, book3; declares book1,book2,book3 as variables of type struct lib_books. Each declaration, i.e, each variable book1, book2, book3 consists of four members of the structure lib_books. Memory Map of structure variable book1 is as shown. Each member of the structure is allocated memory according to its type (int, char etc) and total memory allocated to variable book1 is the “sum” of memory allocated to all its members. book1.title book1.author book1.pages book1.price book1 The complete structure declaration might look like this: struct lib_books { char title[20]; // title, author etc are members of the structure char author[15]; int pages; float price; }; // create a structure template with members void main ( ) { struct lib_books, book1, book2, book3; // create 3 structure type variables …. } We can also combine both template declaration and variables declaration in one statement as shown here:
  • 3.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 3 struct lib_books { char title[20]; char author[15]; int pages; float price; } book1, book2, book3; // declare a structure template and create 3 variables where, book1,book2,book3 are structure variables representing 3 books but does not include a tag name for use in the declaration. A structure is usually defined before main along with macro definitions. In such cases, the structure assumes global status and all the functions can access the structure. 4.1 Accessing & initializing Structure Members: The link between a structure member and a structure variable is established using the member access operator ‘.’ which is known as dot operator and is used to access individual structure element. For example, we can access the member ‘price’ belonging to structure variable book1 as book1. price.  The assignment (=) operator can be used to give values to structure members. book1.pages=250; book1.price=28.50;  We can also use scanf statement to assign values like scanf(“%s”, book1.file); scanf(“%d”, &book1.pages); Consider another example: struct student { int id; char name[10]; float avg ; } a , b , c; Here, we create a structure named “student” and define 3 variables a, b, c of type “student”. The items id, name, avg are known as structure members. a.id - refers to the member named “id” of the structure variable a. scanf( “%d”, &a.id); this statement can accept an integer roll number of structure “a” from user. e.g. struct book { char name; int pages; float price; }; // structure declaration We can declare a structure variable (say z) and initialize as: struct book z = { ‘s’, 125, 90.0}; Here, z.name is ‘s’. z.pages is 125 and z.price is 90.0
  • 4.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 4 /* Example program using structures */ #include<stdio.h> struct student { int id_no; char name[20]; char address[20]; int age; } s1; void main( ) { printf("Enter the student information"); printf("Now Enter the student id_no"); scanf("%d", &s1.id_no); printf("Enter the name of the student"); scanf("%s", s1.name); printf("Enter the address of the student"); scanf("%s", &s1.address); printf("Enter the age of the student"); scanf("%d", &s1.age); printf("Student informationn"); printf("student id_number=%dn", s1.id_no); printf("student name=%sn", s1.name); printf("student Address=%sn", s1.address); printf("Age of student=%dn", s1.age); }
  • 5.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 5
  • 6.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 6 4.2 Array of Structures: It is possible to define an array of structures. For example, if we are maintaining information of all the students in the college and if 100 students are studying in the college, then we need to use an array than single structure variables. We can define an array of structures as shown in the following example: struct { int id_no; char name[20]; char address[20]; int age; } student[100]; An array of structures can be assigned initial values just as any other array. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below. #include<stdio.h> struct student // structure type declaration { int id_no; // 4 data members in the structure char name[20]; char address[20]; int age; }stu[100]; // create 100 variables of structure student // i.e., array of structures just like array of 100 integers void main( ) { int k, n; printf("Enter the number of students"); scanf("%d",&n); printf(" Enter Id_no,name address & age of students n"); for(k=0;k<n; k++) scanf ("%d %s %s %d", &stu[k].id_no, stu[k].name, stu [k].address, &stu[k].age); printf("n Student information details are: "); for (k=0;k< n;k++) printf("%d %s %s %d n", stu[k].id_no, stu[k].name, stu [k].address, stu[k].age); } // end of main
  • 7.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 7 4.3 Structure within a structure (Nested Structures) A structure may be defined as a member of another structure. In such contexts, the declaration of the embedded structure must appear before the declarations of other structures. Ex: struct date { int day; int month; int year; }; struct student { int id_no; char name[20]; char address[20]; int age; struct date doa; // “date” is a structure defined earlier struct date dob; } oldstudent, newstudent; the structure student contains another structure date as its one of its members. As mentioned earlier, structures can have other structures as members. Say you wanted to make a structure that contained both date and time information. One way to accomplish this
  • 8.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 8 would be to combine two separate structures; one for the date and one for the time. For example, struct date { int month; int day; int year; }; struct time { int hour; int min; int sec; }; struct new_date { struct date today; struct time now; }; • here, “new_date” a structure whose elements (members) are nothing but two other previously declared structures. 4.4. Structures as Function Arguments: We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we don’t effect its corresponding argument. i.e., the structure is “passed by value”; so, actual arguments in the calling function are not modified. a) Passing structure elements to functions: A structure may be passed into a function as individual member or a separate variable. A program example to display the contents of a structure passing the individual elements to a function is shown below. #include<stdio.h> struct emp // structure declaration { int emp_id; // structure members char name[25]; char department[10]; float salary; }; void display(int, char [ ]); // function declaration void main( ) { static struct emp emp1={125,"RAMESH", "ECE", 50000.00}; display(emp1.emp_id, emp1.name); // function call with two members of the structure // passed to function as individual variables } // end of main /* function to display structure member values */ void display(int e_no, char e_name[ ]) { printf("%d %s", e_no, e_name); }
  • 9.
    Programming in C& Data Structures 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 9 b) Passing entire structure as argument to a function #include<stdio.h> struct dob // structure declaration { short int dd, mm, yy; // structure members }; void display (struct dob d) ;// function declaration with structure as argument void main( ) { struct dob d1; // creating structure variable d1 of type dob printf (“n enter your date of birth as date, month & year n”); scanf (“%d %d %d” , &d1.dd, &d1.mm, &d1.yy); display(d1); // function call with structure as argument } // end of main /* function to display structure member values */ void display(struct date x) { printf (" Your date of birth is : n”); printf (“%d - %d - %d", x.dd, x.mm. x.yy); } 4.5 Pointers to Structures: One can have pointer variable that contain the address of complete structures, just like with the basic data types. Structure pointers are declared and used in the same manner as “simple” pointers. In C, there is a special symbol -> which is used as a shorthand when working with pointers to structures. It is officially called the structure pointer operator (arrow operator). Its syntax is struct_ptr->member Note: *(struct_ptr).member is same as struct_ptr->member Ex: struct student { int id; char *name; } stu1, stu2 ; // create 2 variables stu1 and stu2 of type struct student void main ( ) { struct student *stp; // stp is a pointer variable stp = &stu1; // stp holds the address of stu1 i.e., stp “points” to stu1 // initializing structure members using pointer variable and dot operator (*stp).id=38; // same as stu1.id = 38; (*stp).name="Ramya"; • Thus, the last two lines of this example could also have been written as: stp->id=38; stp->name="Ramya";