KEMBAR78
Structures: Prof. Indranil Sen Gupta | PDF | Computer Data | Software Development
0% found this document useful (0 votes)
39 views32 pages

Structures: Prof. Indranil Sen Gupta

The document discusses structures in programming and data structures. It defines a structure as a convenient tool for handling logically related data items. A structure allows grouping of complex data into meaningful units. It defines a structure with a tag name and member variables. Structures can be processed by accessing individual members using the dot operator. Arrays of structures and structures within structures are also discussed. Functions can operate on structures by passing them as arguments or returning structures.

Uploaded by

Ankit Katewa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views32 pages

Structures: Prof. Indranil Sen Gupta

The document discusses structures in programming and data structures. It defines a structure as a convenient tool for handling logically related data items. A structure allows grouping of complex data into meaningful units. It defines a structure with a tag name and member variables. Structures can be processed by accessing individual members using the dot operator. Arrays of structures and structures within structures are also discussed. Functions can operate on structures by passing them as arguments or returning structures.

Uploaded by

Ankit Katewa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Structures

Prof. Indranil Sen Gupta


Dept. of Computer Science & Engg.
Indian Institute of Technology
Kharagpur
What is a Structure?

• It is a convenient tool for handling a group of


logically related data items.
– Examples:
• Student name, roll number, and marks.
• Real part and complex part of a complex number.

• This is our first look at a user-defined data type and a


complex data structure.
– Helps in organizing complex data in more meaningful way.
• The individual elements of a structure are called
members.

Autumn Semester 2019 Programming and Data Structure 2


Defining a Structure

• A structure may be defined as:

struct tag {
member 1;
member 2;
:
member m;
};

– struct is the required keyword.


– tag is the name of the structure.
– member 1, member 2, … are individual member declarations.

Autumn Semester 2019 Programming and Data Structure 3


Defining a structure (contd.)

• The individual members can be ordinary variables,


pointers, arrays, or other structures.
– The member names within a particular structure must
be distinct from one another.
– A member name can be the same as the name of a
variable defined outside of the structure.
• Once a structure has been defined, the individual
structure-type variables can be declared as:
struct tag var_1, var_2, …, var_n;

Autumn Semester 2019 Programming and Data Structure 4


Example

• A structure definition:
struct student {
char name[30];
int roll_number;
int total_marks;
char dob[10];
};

• Defining structure variables:


struct student a1, a2, a3;

A new data-type
Autumn Semester 2019 Programming and Data Structure 5
A Compact Form

• It is possible to combine the declaration of the structure


with that of the structure variables:

struct tag {
member 1;
member 2;
:
member m;
} var_1, var_2,…, var_n;

• In this form, tag is optional.

Autumn Semester 2019 Programming and Data Structure 6


Equivalent Declarations
struct student {
char name[30];
int roll_number;
int total_marks;
char dob[10];
} a1, a2, a3;

struct {
char name[30];
int roll_number;
int total_marks;
char dob[10];
} a1, a2, a3;

Autumn Semester 2019 Programming and Data Structure 7


Processing a Structure

• The members of a structure are processed individually,


as separate entities.
• A structure member can be accessed using the dot
operator as:
variable.member
where variable refers to the name of a structure-type
variable, and member refers to the name of a member
within the structure.
• Examples: a1.name, a2.name, a3.dob,
a1.roll_number, a3

Autumn Semester 2019 Programming and Data Structure 8


Example: Complex number addition

#include <stdio.h>
main()
{
struct complex
{
float real;
float cmplex;
} a, b, c;

scanf (”%f %f”, &a.real, &a.cmplex);


scanf (”%f %f”, &b.real, &b.cmplex);

c.real = a.real + b.real;


c.cmplex = a.cmplex + b.cmplex;
printf (”\n %f + %f i”, c.real, c.cmplex);
}

Autumn Semester 2019 Programming and Data Structure 9


Defining data type: using typedef

• One may define a structure data-type with a single name.

• General syntax:
typedef struct {
member-variable1;
member-variable2;
.
member-variableN;
} tag;

• tag is the name of the new data-type.

Autumn Semester 2019 Programming and Data Structure 10


typedef : An example

typedef struct{
float real;
float imag;
} _COMPLEX;

A new data type


_COMPLEX a, b, c;

Autumn Semester 2019 Programming and Data Structure 11


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:
_COMPLEX a={1.0,2.0}, b={-3.0,4.0};

a.real=1.0; a.imag=2.0;
b.real=-3.0; b.imag=4.0;

Autumn Semester 2019 Programming and Data Structure 12


Comparison of Structure Variables

• Unlike arrays, group operations can be performed


with structure variables.
– A structure variable can be directly assigned to another
structure variable of the same type.
a1 = a2;
• All the individual members get assigned.
– Two structure variables can be compared for equality or
inequality.
if (a1 == a2)……
• Compare all members; return 1 if they are equal; 0 otherwise.
– Direct arithmetic operations are not possible with
structure variables
Autumn Semester 2019 Programming and Data Structure 13
Arrays and Structures

14
Arrays within Structures

• A structure member can be an array:


struct student
{
char name[30];
int roll_number;
int marks[5];
char dob[10];
} a1, a2, a3;

• The array element within the structure can be


accessed as:
a1.marks[2]

Autumn Semester 2019 Programming and Data Structure 15


Arrays of Structures

• Once a structure has been defined, we can


declare an array of structures.
struct student class[50];

– The individual members can be accessed as:


class[i].name
class[5].roll_number
class[20].marks

– What is class[20].marks[2] ?

Autumn Semester 2019 Programming and Data Structure 16


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); 17
Structures and Functions

18
Structures and Functions

• A structure can be passed as argument to a function


– Structure variables can be passed as parameters like any
other variables
– Only the values will be copied during function call
• A function can also return a structure

• Rules are very similar to the scenario when an int /


float is passed as argument or returned from a
function

19
An example function operating on structures

_COMPLEX add (_COMPLEX a, _COMPLEX b)


{
_COMPLEX tmp;

tmp.real = a.real + b.real;


tmp.imag = a.imag + b.imag;

return(tmp);
}

Autumn Semester 2019 Programming and Data Structure 20


Example: Addition of two complex numbers
#include <stdio.h>
int main()
typedef struct { {
float real; _COMPLEX num1, num2, sum;
float imag;
} _COMPLEX; scanf ("%f %f", &num1.real,
&num1.imag);
scanf ("%f %f", num2.real,
_COMPLEX add (_COMPLEX a, _COMPLEX b)
&num2.imag);
{
_COMPLEX tmp;
sum = add (num1, num2);
printf ("\nSum is: %f + i %f",
tmp.real = a.real + b.real;
sum.real, sum.imag);
tmp.imag = a.imag + b.imag;
}
return(tmp);
}

Autumn Semester 2019 Programming and Data Structure 21


Example: Compute perimeter of polygon
#include <stdio.h>
int main()
typedef struct { {
int sides; POLYGON shape;
float length[10]; int k;
} POLYGON; float peri;

scanf (”%d”, &shape.sides);


float perimeter (POLYGON p)
for (k=0; k<shape.sides; k++)
{
scanf (”%f", &shape.length[k];
float peri = 0.0;
int i;
peri = perimeter (shape);
printf ("\nPerimeter is: %f",
for (i=0; i<p.sides; i++)
peri);
peri += p.length[i];
}
return(peri);
}

Autumn Semester 2019 Programming and Data Structure 22


Structures are also passed to functions by value

• When a structure variable is passed as argument to a


function
– Only the value of the structure variable will be copied (to the
formal argument) during function call
– Rules are similar to when an int / float is passed as argument

23
An example: swapping structures
#include <stdio.h>

typedef struct {
float real;
float imag;
} _COMPLEX;

void swap (_COMPLEX a, _COMPLEX b)


{
_COMPLEX tmp;

tmp = a;
a = b;
b = tmp;
}

Autumn Semester 2019 Programming and Data Structure 24


Example:: contd.
void print (_COMPLEX a)
{
printf("(%f, %f) \n“, a.real, a.imag);
}

main()
{
_COMPLEX x = {4.0,5.0}, y = {10.0,15.0};

print(x); print(y);
swap(x,y);
print(x); print(y);
}

Autumn Semester 2019 Programming and Data Structure 25


• Output:
(4.000000, 5.000000)
(10.000000, 15.000000)
(4.000000, 5.000000)
(10.000000, 15.000000)

• No swapping takes place, since only values are


passed to the function. The original variables in
the calling function remains unchanged.

Autumn Semester 2019 Programming and Data Structure 26


Size of a structure

27
Estimating the Size of a Structure

• The “sizeof” for a struct variable is not always


equal to the sum of the “sizeof” of each individual
member
– Padding (extra space) can be added by the compiler to
avoid alignment issues
– Padding is only added when a structure member is
followed by a member with a larger size, or at the end
of the structure
• Exact convention may vary from one compiler to
another
Autumn Semester 2019 Programming and Data Structure 28
(a) Example 1
#include <stdio.h>
int main()
{
struct A { Here, x (int) is followed by z
// sizeof(int) = 4 (double), which is larger in size
int x; than x. Hence padding is required
// Padding of 4 bytes after x. Also, padding is required
// sizeof(double) = 8
at the end for data alignment.
double z;
// sizeof(short int) = 2
short int y;
// Padding of 6 bytes
};
printf("Size of struct: %ld", sizeof(struct A));
return 0;
}
Size of struct: 24

Autumn Semester 2019 Programming and Data Structure 29


(b) Example 2
#include <stdio.h>
int main()
{
struct B { The members of the structure are
// sizeof(double) = 8 sorted in decreasing order of their
double z; sizes. Hence padding is required
// sizeof(int) = 4 only at the end.
int x;
// sizeof(short int) = 2
short int y;
// Padding of 2 bytes
};
printf("Size of struct: %ld", sizeof(struct B));
return 0;
}
Size of struct: 16

Autumn Semester 2019 Programming and Data Structure 30


(c) Example 3
#include <stdio.h>
int main()
{
struct C { Here, y (short int) is followed by x
// sizeof(double) = 8 (int) and hence padding is
double z; required after y. No padding is
// sizeof(short int) = 2 required at the end.
short int y;
// Padding of 2 bytes
// sizeof(int) = 4
int x;
};
printf("Size of struct: %ld", sizeof(struct B));
return 0;
}
Size of struct: 16

Autumn Semester 2019 Programming and Data Structure 31


Exercise 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.
• Write a function to compute the distance between two given points.
• Write a function to compute the middle point of the line segment
joining two given points.
• Write a function to compute the area of a triangle, given the co-
ordinates of its three vertices.
3. Define a structure to represent students’ information (name, roll number,
cgpa). Read the data corresponding to N students in a structure array, and
find out the students with the highest and lowest cgpa values.

Autumn Semester 2019 Programming and Data Structure 32

You might also like