Structures
…. and other user-defined data types
1
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Basic Definitions
2
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
What is a Structure?
It is a convenient construct for representing a group of logically related data items.
• Examples:
• Student name, roll number, and marks.
• Real part and complex part of a complex number.
Structures help in organizing complex data in a more meaningful way.
The individual structure elements are called members.
This is our first look at a user-defined data-type.
3
Defining a Structure
The composition of a structure may be defined as:
struct á name of structure ñ {
á data-type ñ á member-name1ñ ;
á data-type ñ á member-name2ñ ;
…
á data-type ñ á member-namekñ ;
};
For example:
struct point {
float xcoord;
float ycoord;
};
4
Example
A structure definition • struct is the required C keyword
• Do not forget the ; at the end of the structure defn
struct student {
char name[30];
int roll_number; • The individual members can be ordinary
int total_marks; variables, pointers, arrays, or other structures
char dob[10]; (any data-type)
};
• The member names within a particular structure
Defining structure variables: must be distinct from one another
• A member name can be the same as the name of a
struct student a1, a2, a3; variable defined outside of the structure
A new data-type
5
Structure Definition versus Structure Variable Declaration
Structure Definition Structure Variable Declaration
struct point { struct point a, b, c;
float xcoord;
float ycoord;
}; • Here a, b, c are variables of the
type struct point
• No memory is allocated • Memory is allocated for a, b, c.
• Only defining a new data-type • Variable declaration is possible
after definition
Each structure type variable (e.g., a, b, c) has its own copy of each member
of that structure type
6
Structure Variable Declaration can be clubbed with Definition
Separately: Together: Another way:
struct point { struct point { struct {
float xcoord; float xcoord; float xcoord;
float ycoord; float ycoord; float ycoord;
}; } a, b, c; } a, b, c;
struct point a, b, c; • The struct definition can • In this case we do not have
be reused elsewhere a name for the struct
• Like: • Hence we cannot reuse the
struct point p, q; struct definition
Each structure type variable (e.g., a, b, c) has its own copy of each member
of that structure type
7
Type Definitions
8
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
The typedef construct
The typedef construct can be used to define new (derived) data types in C.
typedef float kilometers_per_hour; // kilometers_per_hour is a new data type
// Note that no variable is allocated space here
kilometers_per_hour speed; // Here speed is a declared variable
speed = 40;
9
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Structures and typedef
Without typedef With typedef
struct complex typedef struct
{ {
float real; float real;
float imag; float imag;
}; } complex ;
struct complex a, b, c; complex a, b, c;
Here struct complex is like a Here complex is a new data
new data type. type
10
Accessing members and using structures
11
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Accessing the members of a structure
• The members of a structure are accessed individually, as separate entities.
• A structure member can be accessed by writing Dot operator used to access
members of a structure, through a
ávariable-nameñ.ámember-nameñ structure-type variable
where variable refers to the name of a structure-type variable, and member refers to the
name of a member within the structure.
struct point {
float xcoord;
float ycoord;
} a, b;
a.xcoord = 2.5; a.ycoord = 3.2;
b.xcoord = b.ycoord = 0;
12
Structure initialization
Structure variables may be initialized following similar rules of an array.
The values are provided within the second braces separated by commas
An example:
struct complex a={1.0,2.0}, b={-3.0,4.0};
a.real=1.0; a.img=2.0;
b.real=-3.0; b.img=4.0;
13
Example: Addition of two complex numbers
#include <stdio.h>
main( )
{
struct complex
{ Structure declaration can be outside
main() as well. This is necessary if a
float real;
program has multiple functions using
float imag; a structure type.
} a, b, c;
scanf (“%f %f”, &a.real, &a.imag);
scanf (“%f %f”, &b.real, &b.imag);
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
printf (“\n %f + %f j”, c.real, c.imag);
}
14
Assignment of Structure Variables
main()
struct class {
{ int x;
int number; struct class student1 = {111, "Rao", 72.50};
char name[20]; struct class student2 = {222, "Reddy", 67.00};
float marks; struct class student3;
};
student3 = student2;
}
A structure variable can be directly assigned to another variable of the same type.
All the individual members get assigned / copied.
But, two structure variables can NOT be compared for equality or inequality
if (student1 == student2)…… this cannot be done
15
An interesting observation
int a[5] = { 10, 20, 30, 40, 50 }; struct list {
int b[5]; int x[5];
};
b = a;
struct list a, b;
X This is not allowed a.x[0] = 10; a.x[1] = 20;
a.x[2] = 30; a.x[3] = 40;
a.x[4] = 50;
b = a;
This is allowed !!
Structures can be copied directly – even if they contain arrays !!
16
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Arrays of structures
17
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Arrays of Structures
Once a structure data-type has been defined, we can declare an array of structures.
struct class
{
int number;
char name[20];
float marks;
};
struct class student[50];
• The individual members can be accessed as:
student[ k ].marks marks of the kth student
student[ k ].name name of the kth student
student[ k ].name[ j ] jth character in the name of the kth student
18
Example: Store a list of students (name, CGPA), compute
average CGPA
#include <stdio.h>
// compute average cgpa
struct student{ avg = 0.0;
float cgpa; for(i=0;i<5;i++)
char name[10]; avg += st[i].cgpa;
};
avg = avg / 5.0;
int main( ){ printf(“Avg cgpa:%f”,avg);
int i; float avg;
struct student st[5]; return 0;
printf(“Enter records of 5 students”); }
for(i=0;i<5;i++){
printf("\nEnter Cgpa:");
scanf("%f",&st[i].cgpa);
printf("\nEnter Name:");
scanf("%s”,st[i].name);
}
19
Structures and functions
20
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Structures are passed by value to functions
#include <stdio.h> void print ( _COMPLEX a)
{
typedef struct { printf("(%f, %f) ", a.real, a.imag);
float real; }
float imag;
} _COMPLEX; main( )
{
void swap ( _COMPLEX a, _COMPLEX b) _COMPLEX x = { 4.0, 5.0 }, y = { 10.0, 15.0 };
{
_COMPLEX tmp; print(x); print(y); printf(“\n”);
swap(x, y);
tmp = a; a = b; b = tmp; print(x); print(y); printf(“\n”);
} }
Program output: No swapping takes place actually,
(4.000000, 5.000000) (10.000000, 15.000000) similar to what we saw for integers,
(4.000000, 5.000000) (10.000000, 15.000000) floats, etc.
21
Structures can be returned from functions
#include <stdio.h> main( )
{
typedef struct { _COMPLEX x = { 4.0, 5.0 }, y = { 10.0, 15.0 };
float real; _COMPLEX z;
float imag;
} _COMPLEX; z = add(x, y);
printf(“ %f, %f \n”, z.real, z.imag);
}
_COMPLEX add ( _COMPLEX a, _COMPLEX b)
{
_COMPLEX tmp;
Program output:
tmp.real = a.real + b.real; 14.000000, 20.000000
tmp.imag = a.imag + b.imag;
return tmp;
}
22
Pointers to Structures
23
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointers and Structures
struct class
{
int roll;
char name[20];
float marks;
};
struct class* ptr;
Once ptr points to a structure variable, the members can be accessed as:
ptr –> roll;
ptr –> name;
ptr –> marks; Arrow operator used to access
members of a structure, through a
• The symbol “–>” is called the arrow operator. structure-type pointer.
24
Use of pointers to structures
#include <stdio.h>
struct complex {
float real;
float imag; void add (struct complex* x, struct complex* y,
}; struct complex* t)
{
main( ) t->re = x->real + y->real;
{ t->im = x->imag + y->imag;
struct complex a, b, c;
}
scanf ( “%f %f”, &a.real, &a.imag );
scanf ( “%f %f”, &b.real, &b.imag );
add( &a, &b, &c ) ;
printf ( “\n %f %f”, c,real, c.imag );
}
25
A Warning
When using structure pointers, we should take care of operator precedence.
• Member operator “.” has higher precedence than “*”
ptr –> roll and (*ptr).roll mean the same thing.
*ptr.roll will lead to error.
• The operator “–>” enjoys the highest priority among operators.
++ptr –> roll will increment roll, not ptr.
(++ptr) –> roll will increment the pointer (to the next structure in an array) and
access roll in the next structure.
26
Practice problems
1. Extend the complex number program to include functions for addition,
subtraction, multiplication, and division
2. Define a structure for representing a point in two-dimensional Cartesian co-
ordinate system. Using this structure for a point
i. Write a function to return the distance between two given points
ii. Write a function to return the middle point of the line segment joining
two given points
iii. Write a function to compute the area of a triangle formed by three given
points
iv. Write a main function and call the functions from there after reading in
appropriate inputs (the points) from the keyboard
27
3. Define a structure STUDENT to store the following data for a student: name
(null-terminated string of length at most 20 chars), roll no. (integer), CGPA
(float). Then
1. In main, declare an array of 100 STUDENT structures. Read an integer n
and then read in the details of n students in this array
2. Write a function to search the array for a student by name. Returns the
structure for the student if found. If not found, return a special structure
with the name field set to empty string (just a ‘\0’)
3. Write a function to search the array for a student by roll no.
4. Write a function to print the details of all students with CGPA > x for a
given x
5. Call the functions from the main after reading in name/roll no/CGPA to
search
28
Unions
29
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Union
• In a struct, space is allocated as the sum of the space required by its members.
• In a union, space is allocated as the union of the space required by its members.
• We use union when we want only one of the members, but don’t know which one.
Suppose we wish to store an ID for each employee.
• Some employees may provide passport ID (8 characters)
• Other employees may provide Aadhar Card Number (12 digit integer)
• If we use a structure with both these fields, we will waste space
30
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Union example
main ( )
typedef union { {
char passport[9]; struct employee x;
int aadhar; … read employee name and employee code here …
} id ; printf(“What is your ID type: \n 1. Passport, 2. Aadhar\n”);
scanf(“%d”, x.idtype);
struct employee {
char empname[20]; if (idtype == 1) {
int empcode; printf(“ Enter passport number: “);
int idtype; scanf( “%8s”, x.id.passport ) ;
id idnumber; }
}; if (idtype == 2) {
printf(“Enter Aadhar card number:”);
scanf(“%12d”, x.id.aadhar );
}
}
31
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR