Application Programming in C by RS Salaria - Structures
Application Programming in C by RS Salaria - Structures
Structures
seen how a simple variable (i.e. scalar variables) can hold one value at a time and how
We bave mechanisms
hold a number of values of the same data type. These two data storage
arrays can data items of different types
can
handle a wide variety of problems. But we often want to process
asa unit. In this case, neither the scalar variable nor the array is adequate.
together
to store information of employees in an organization. This information may
Suppose we want
include en1ployee'ssoname (character array), department code (integr number), salary (floating
and forth. And we want our program to deal with them as elements of an array.
point number),
possible approachisto use several arrays acharacter array for names, an integer arrayfor
One
department code, a floating point array for salary, and so forth. And using common index we can
access theinformation for a particular employee, but this
relatedI to asingle approach obscures the fact that we are
with data items entity, an
dealing employee
in our example.
To solve this sort of problem, Cprovides a special data type: the structure. You canthink of a
structure as group of data items of different data types held together in a Single unit. Inour
example, structure would consist of employee's name, department number, salary, andsoforth.
Declaring a Structure
The fundamental
Thus when
data types, such as
we use an
integer integer,
variable, we real' or
Structures
and
Unions 199
will interpret the contents of
being that a these two know
bytes in
it
al w ays charactoccupi
are er, es pre-defined
reason structure
programmer must tell the
can a
contain any numbercertainof way. This istwo bytes, tby the
compiler how the structure willdata items of not true forand theeomiler.
type.
different data types.eomoiSolTheer
look like before struactbluerses.of the
using vari
The syntax for declaring a structure is that
struct sname
type varl;
cype var2;
type var3;
type varN;
where struct is a keyword to define a structure, sname is the name given to the structure data
type, type is a built-in data type, and varl, var2, var3,.. ., varN are elements of the structure
being defined.
The sname is called the tag and it gives a name to the structure being defined. The portion of the
structure definition enclosed in braces is known as a structure template. The structure tag is
optional. The use of structure tag makes it possible to declare other variable of the same structure
Ype without having to rewrite the template itself. Note that it is not a variable name, since we are
not declaring a variable; it is a ypename.
Consider our previous example, to store the information of an employee, our structure
declaration may look like as shown below.
struct employee type
int code;
Char name [20];
int dept code;
float salary;
PlStAeasasie dnote e that no
for this yariable has been associated with the structure at this point and no memory 1s
structure.
198 Application Programmingtn C
varl 1197
1198
L1199
var2 1200
1201
1202
1203
1204
var3
1205
1206
1207
1208
var4
1209
1210
1211
Initializing Structures
arrays, structure variables can also be initialized at declaration time.
Lke simple variables and
is quite similar to that used to initialize arrays. The following segment illustrates
lhe format used
this
int rollno;
char name [25];
int agei
float height i
:
"Surbhi Salaria" , 18, 5.6
1000,
student = {
struct student type
in C
200
Application Programming
AccessingStructure Elements
In arrays, we can
access individual elements with a
subscript. For example, to access 7h elemet
of one-dimensional array named height, we write height[6]. However
approach. The elements of a structure variable are accessed using dot structures
uses diferent
operator provides a powerful and clear way to refer to an individual element operator.The de
of a
Syntax for accessing members of a structure using dot operator is: structure. The
Sname.vname
main ()
type employee;
struct employee employee's code : " );
printf ( "\nEnter
&employee. code )
employee's name :" );
scanf ("%d,
("Enter
printf employee.name );
gets ( employee's department :
printf ("Enter department );
employee.
gets (
("Enter employee's salary
printf &employee. salary ); user\n"
(%f", employee as entered by
scanf ("\n\nParticulars of employee. code )i
printf ("\nEmployee's code : %d", I employee.name );
employee.department )i
printf ("\nEmployee's name
department : employee. salary);
("\nEmployee's 2f\n"
printf ("Employee's salary : %.
printf
SIructures and Unions 201
Use of Assignment Statement for Structures
The value of one structure
variable can be
simple assignment statement. For example, assigned to another variable
if studentl and student2 of the same type
type.student ype, then the following
assignment statement are
structure usingof
student2 = studentl;
variables
assigns value of structure variable studentl to student2. This is
when you think about it. When you assign one rather an amazing
Wcsigned to corresponding structure structure tO another, all the values in the capability
ar for arrays. That is, to assign one elemnents. Simple assignment statement cannot structure
array to another, we have to assign element by be used
element.
Pointers and Structures
. e can use pointers With other data types, we can alsO use
pointers for structure variables.
Consider the following declaration
struct student_type student, *ptr;
.Jolares a structures variable student and a pointer variable ptr to structure of type
student type. The pointer variable pir can be initialized with the following assignment statement
ptr = &student;
Having initialized the pointer variable pIr, the nextquestion is -Howwe can access elements of
the structure? We already know that ifpis apointer variable pointing to a value of type integer,
real, or character, the value pointed to by the pointer variable can be accessed by the expression
.You may think that the elements of the structure pointed to by ptrcan also be accessed as
*ptr.rollno, *ptr,name, *ptr.age, *ptr height
Dt this approach will not work as the dot operator. ' has higher priority than the_indirection
Jperator * The correct way is to write as
ptr->vname
where ptr is pointer the name of
element of the
structure. variable pointing to a structure, and vname is
Using arrow operator, the elements of structure of type student type pointed to by pointer
variable ptr can be accessed as
ptr->rollno, ptr->name, ptr->age, ptr->heignt
int dayi
int month ;
int yeari
main ()
1997 }:
date d = { 10, 12,
struct date ) ;:
print date ( struct
void (d ):
print,date
date ( struct date a )
Void print
("\nDate. in format day/month/year is %d/%d/%d\n,
printf a.day,a.month, a.year );
arrays and structures, the more efficient method is using pointers i.e. by
However, to pass have to pass
it,
reference. In addition to if the function can modify the structure variable, then we variable can
the structure
variable by reference. The next program illustrates the way a structure
reference.
be passed by
Program Listing 9.3
/**t******* **** t
int day;
int onth;
int year;
main ()
struct date d;
Void get date ( struct
printf (\nEnter date date * )i
in format
get date ( &d ); day/month/year
printí ("\nDate entered hy uon is &d/8d/8d\n", d.day, d.month, d. year ;
void get_ date ( struct date *a
scanf (%d/d/%d", &a->dav, sa->month, &a->year i
#include <stdio.h>
struct date
int day;
int month;
int yeari
main()
struct date d;
Struct date get date (void ) ;
Printf ( "\nEnter date in fomat day /month/year : " );
d= get date (); d.day, d.month, d. year );
Printf "\nDate entered by you is %d/%d/%d\n",
struct date ai
OGanf ( "%d/%d/%d, &a. day, &a.month, &a. year );
return a;
Array of Structures
We have considered structure variables, which can store one value of
to process a list of values of structure type, then we structure
need an array of such type. If we wish
structures,
Declaring an Array of Structures
Suppose we want to store and process information
of 50
department andemployees
have data about employee's code, name, of an
do the job. organization, where
salary. The following
struct employee type declarations wil
int code;
char name [25];
char department (15];
float salaryi
*include <stdio.h>
#include <conio.h>
struct employee type
int code;"
char name [25];
char department (15] :
float salary:
}:
struct employee. type employee (50];
int n = 0;
void input ( void ):
Structures and Unions 205
void
main ()display (void ):
{
int option;
while (1 )
clrscr () ;
printf ("\nSelect one of the
printf ( "\n- following options" )i
printf ( "\n 1
printf ("\n 2 Enter new employee" )
printf ( "\n 3, Display list. of employees" )i
printf Exit from program i
("\n
scanf ( "&d \nEnter your option (1-3) : " )i
if ( ( &option )}
option < 1 ) | optioH >3 ) )
Continue;
sWitch ( option )
case 1: input ();
break;
case 2 : display();
break;
case 3 : exit (1) ;
printf ("\nList
( of employees \n\n" ):
LOr ( i = 0: i < n; i++ )
Nested Structures
Iust as there can be arrays of arrays, there can
also be structures that contain other struchures
This can be a powerful way to create
complex data types. The only restriction on nesting of
structures is that a structure cannot contain a
(i.e. with the same tag) as the outer structure. member that is itself a structure of the same tye
int day:
int month;
int year;
int day;
int month;
int yeari
) date of_joiningi
char department [15];
float salaryi
employee
struct employee type
Structures and Untons 207
ofNested Structures
Accessing Elements
of a nested structure are accessed by referring to structure variable name,
Individyal elements
operator, followed by inner structure variable name, followed by dot operator,
followed by dot the structure element desired. In our example, suppose we want to
and endingwith access the
employee, w can. do so by writing
joining ofan
year of employee.date of joining.yeari
at this level; we can nest a structure within a structure within a
process need not stop
The nesting
structure.
Self-referentialStructures
that include an element that is a pointer
to another
structures complex data
self-referential structures_are structures find their application in building self-referential
type. These of
The
structure of the same graphs. To illustrate the processing
and
structure such
as linked lists, trees oflinkedlist.
structures, let us consider the example
example
Linked Lists: An elements, called nodes. Pointers give the
data list
linear collection of homogeneous parts. A linked list can be linear linked
Alinked list is a more linked
Each node is divided into twO or
this section, we will consider linear
linear order. linked list (two-way list). In
(one-way list) or doubly
list.
START 1202
1203 X
1200 1201
second node
Next pointer field of
node
Information field of second
int option;
start = last ptr = ( node * ) NULL;
while ( 1 )
clrscr ();
printf ( "\nSelect one of the following options" ):
printf ( "\n-- ):
printf ("\n 1 Enter new employee" ):
printf ( "\n 2 Display list of employees" ):
printf ( "\n 3
Exit from program" );
printf ( "\n\nEnter your option (1-3): " ):
scanf.( "%d", &option );
if ( ( option < 1 ) | | (option > 3 ) )
continue;
switch ( option )
case 1 :
input ():
Structures und Jnonn
case 2 : break;
display ():
break;
case.3 : delete():
exit (1) ;
Functionally, program listing 9.6 is equivalent to program listing 9.5, but it needs some furher
explanation.
The declaration portion includes two pointers start and lastptr, which holds the address of the
first element and the last element of the list respectiveiy.
To begin with,the start and last ptr variables are set to NULL Value by the statement
start = last ptr = ( node * ) NULL;
to indicate that list is initially empty. The constant NULL (also called macro) is defined as va
0 in header file stdio.h. Since this value is to be assigned to a pointer, it must be typecast
is same as In prug
same type as the pointer variable is.The main) function in other aspectsincorporated
which is to re
listing 9,5 except it contains call to one more function delete)
the list from memory before the program terminates.