0% found this document useful (0 votes)
495 views

Application Programming in C by RS Salaria - Structures

This is the first part of the topic Structures and Unions of the book Application Programming in C by renowned author RS Salaria. This pdf covers topics till Linked Lists.

Uploaded by

Sarvagya Dwivedi
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)
495 views

Application Programming in C by RS Salaria - Structures

This is the first part of the topic Structures and Unions of the book Application Programming in C by renowned author RS Salaria. This pdf covers topics till Linked Lists.

Uploaded by

Sarvagya Dwivedi
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/ 16

CJ196 Application Programming in C

Introduction structure andthe union.


You can think of
permits the
This chapter Important Cconstructs,
the
unlike an array, a structure
describes two
a structure as an related items.However, contiguous memory locations.
array of closely types. These data iterms occupy ways are completely different
data items to be of different data
similar to a structure, but in other data items are stored in same
Unions, which are in some way these
different datatypes. But another value at different time. The
allow you to store data items of one time and requirement are more.
These
at
memory, and store one value of given type item whose memory
data
size of memory allocated depends on the most database and spradsheet programs.
two data structures are the foundation of
per their requirements. This way a user
type defined by the users as data types.
strueture and a union are a newly created data types are known as user-defined
Creates a new data type. These arrays of
structures, access structure elements, create
to build arguments to a
This. chapter describes how self-referential structures, pass structures as
structures, nested structures,
function, and finally about unions.

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

Declaring Variables of Structure Type


Once a structure is defined, we can
variable(s) of structure type is: declare variable(s) of that
type. The syntax
struct Sname
svarl , for
For example, the statement
struct employee_type employee;
svar2,
declaring
eclares a variable
side for the
structureemplvariable
oyee to be of type
Je can also
declare
employee. employee_type. And at this point the
xample, the varia ble(s) of
structure memor y 1s se
an be
combinedempltogether
oyee_typeas shown type
structure declaration andalong with the structure
struct, employee type below. declaring variable of declaration
type
{
int code;
char name [20]:
employee type
int dept code;
float
o
employee salary:
understand
ollowing
how
declarations.the elements of the structure variables are
struct example type stored in memory,
consider the
char varl;
int var2;
float var3;
double var4;
struct example type
samplel;
Figure 9.1 shows a
its conceptual
members are stored view of
in memory. the struct samplel and its
relationship to memory ie. hoW
Variable varl has an
var4 has an address address 1197, var2 has an address
1198, var3 has an
order in which they are1204. Note that all members are stored address 1200, and
declared. in memorylocationin
contiguous
Structures and Unions 199

varl 1197
1198
L1199
var2 1200
1201
1202
1203
1204
var3
1205
1206
1207
1208
var4
1209
1210
1211

structure variable samplel


memory map

Figure 9.1 Structure Variable samplel and Its Relationship to Memory

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

struct student type

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

where sname is structure variable name and vnane is name of the


element of the structure
For example, the element of the structure variable student can be
accessed as student.rol
student.name, student.age, and student.height.

Entering Datainto Structures


The data into a structure can be entered in asimilar manner as done with simple variables a
array variables. The following program illustrates this.
Program Listing 9.1
/** *k *** t** *t ***k *** *
structures
the way the data is entered into
* Program to i1lustrate
***t**
******t**/
*** t
*** t t * t ** t * * * ***
# include <stdio.h>
struct employee_type
name (25];
int code; char
(15]; float salary:
char department

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).rollno, (*ptr) .name, (*ptr).age, (*ptr).! .height


There is another aapproach that is more elegant and simple. In this approach, the elements of
Siucture are accesses using arrow operato ->' which is a combination of two
characters i.e.
hyphen and greater-than
The
syrntax for accessing members of a structure using arrow operator is:

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

Passing Structure to aFunction


variables can also be passed as arguments
Like simple variables and array variables, the structureway a structure variable can be passed by
illustrates the
to afunction. The following program
value.
* *
Program Listing 9.2
* t * ******:
/** t * * * * * * * **** structure variables
illustrate the passing of
Program to **/
function
* by value to a
#include <stdio. h>
struct date

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

am to illustrate the passing of structure variableS


function
by reference tO a
#include <stdio.h>
struct date
Structures and Unions 203

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

Functions Returning Structures


We have already seen that a function can return a value of type integer, real, character or a
pointer via return statement. In addition to a value returned via return statement, a function
could also return values through formal parameters declared as pointers if the actual parameters
return a structure via
are passed by reference. In program 9.3, we have seen how a function can return
formal parameters. A function can also return a value of structure type as well via
statement as illustrated in the next program.

Programn Listing 9.4


a value of
Program to illustrate the function returning
-structure type via return statement

#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 get date ( void )

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

struct employee type employee (50] ;

Accessing Elements of an Array of Structures


Individual elements of a structure in an array of
variable name, followed by subscript, followed structures are accessed by referring to
element desired. In our example, suppose we by dot operator, and ending with the strUC:
structe
so by writing want to access salary of 7th employee, we can
employee (6] .salary
The following program illustrates the input,
processing and output of array of structures.
Program Listing 9.5
Program to illustrate the processing of array of
by storing list of structures
** ** *** *** k *** t*** k** *employees
*** t *** t in memory
k kkk k*k ** k

*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) ;

void input ( void )


clrscr(0:
printf ( "\nEnter employee's code : " ):
scanf ( "%d", &employee [n].code );
printf ( "Enter employee's name
gets ( employee [n] .name );
printf ("Enter employee's department : " ):
gets ( employee [n] .department );
printf ( "Enter employee's salary : " ):
Scanf ( "£" employee[n++) .salary D:
void display ( void )
int i;
clrscr()
if ( n = 0)
printf ("\nList is empty... ")i
printf \nPress any key to continue
) getch ():
els

printf ("\nList
( of employees \n\n" ):
LOr ( i = 0: i < n; i++ )

Print£( "\nEmployee #8d", i+1 );


PEintf ( "\n\nEmployee's code : %d", employee [i) . code ):
Printf ( "\nEmployee's name : employee [i].name )
Printf ( "\nEmployee's department : %s"
employee [i].department );
in C
206
Application Programming
salary : %.2£\n!
printf ("\nEmployee' skey to continue
printf ( \nPress any
employee (i] .salary );
getch ();

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

As an example, suppose we want to


an employee in the employee type include we
additional information regarding date of joining of
structure, can do so as shown below.
struct date

int day:
int month;
int year;

struct employee type


int code;
char name [25]:
struct date date of joining;
Char department [15]
float salaryi

struct employee type employeei


or we can also do as

struct employee type


int code;
char name [25];
struct date

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

integer values with nodes 4


gure 9.2 Linear linked list of
208
Application Programming inC
In linear
linked lists, each node is divided into two parts:
irst part contains the information of the
element, and
Second part, called the link field'or nextnotnter field, contains the address of the next nod.
inthe list.
In addition,
first elementanother pointer
ot the list. Andvariable, for example START, is used that contains the
the last element of the linked have NULL value in theaddress of the
field (pictured as Xin the
traversed only in one direction.pointer
nextpointer
field) to mark the end of the list. Linear linked lists
can be
Let us consider the problem of
maintaining a list of employees using linear linked list. At
Stage wemay want to add a newemployee or to display the existing list. any
Program
/**k***t Listing
k*******9.6
Program to illustrate the processing of linear linkedlist
by storing a list of employees in
tt*t *** ******k memorY
#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <conio.h>
typedef struct employee type
{
int code;
char name (25] ;
char department (15];
float salary;
struct employee type *next;
} node;
node *start, *last ptr:
void input ( void );
void display ( void ):
void delete ( void ):
main ()

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) ;

oid input ( void )


node *this ptr;
int mcode;
char mname |25J mdepartment [15):
float msalary;
clrscr():
printf ( "\nEnter
scanf"3d"&mcode employee's
): code :"_)
printf ("Enter euployee's name : "
gets( mmame ); );
printf ( "Enter employee's
gets ( mdepartment ); department : " ):
printf ( Enter employee's salary : u
Scanf ( "%f", &msalary );
this ptr = ( node * ) malloc ( sizeof ( node ) ):
this_ptr->code =mcode;
strcpy ( this ptr->name, mname ):
strcpy ( this _ptr->department, mdepartment ):
this ptr->salary = msalary;
this ptr->next=(node *) NULL;
if ( start == ( node * ) NULL )
start = last ptr = this ptr;
else

last ptr->next = this ptri


last ptr = this ptr;

void display ( void )


int i = l;
node *this ptri
clrscr ():
if (
start =s ( node * ) NULL)

Printf("\nList is empty. .. ")i


printf ( "\nPress any key to continue
getch ():
else
printf ( "\nList of employees \n\n" );
for (this ptr=start;this ptr!= (node*) NULL; this ptr=this ptr->next)
printf (" \nEmployee #%d", i );
210 ApplicationProgramming in C

nrintE ( "\n\nEmployee's code : %d, this


ptr->code );
printf ( "\nEmployee's name : %g" this
printf ( "\nEmployee's department : %s" ptr->name );
this ptr->department );
printf ("\nEmployee's salary : %.2£\n this ptr->salary );
printf (\nPress any key t continçe
getch();
i++;

void delete ( void )


{
node *this ptr;
while ( start != ( node * ) NULL )
this ptr = starti
start = start->next;
free ( this ptr )i

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.

Adding an Employee to the List Thistunctù


main) function calls input) function. structure
When the user want to add an employee, the operating System to hold one pointer
local
from the
uses malloc) function to get memory block of this memory block is storedin elementsof
element of type employee type. The address variables is copied into the
correspondingNULLasthis
variable this ptr. The user input in local
to
next pointer element is setafter
it.
block, and the
the structure in the allocated memory will be no element.
end of the list, sothere
structure element will be added at-the
211 the following theThe the
If response
another by the
this,
of of ptr. not. listassigning
statement
of do
Unions element
Structures
and address
this to or elements To entire
the user'sstatement
empty
element
to list.
first by the
set theby the
linkedfirstby
memory.
the
ptr hold is forthe
are structure
listwaits the deletesptr statement
be this prints NULL. task
willptr the from the from
to to this
and this
byfunction
going set ptr last onewhetherthat
structure be variable the removed
empty." occupied
accomplishes
condition are lastand from loop to by
is structure see out
this ptr variable delete) pointer list statement
pointers fornext turns is
last ptr:oisinele to memory the
whether is list
test checksinto
"List the
the ptr function of
followingand pointer
of enterof The local node the
entire
of address this the
that start chainmessage
first to by
element function. the
the it when free start, second
see e both following
this
task delete) list
the satisfied, thedisplay) empty, must
till
to NULLsEe the the
is with
pointer ptr; followthe ends Memory by the loop
then gets =this of
we delete()
ptr->next; to
does this statements
accomplish displays
not The
is
accomplished function ptr, loop pointed to element while
*) notnext this ptr; to is terminates,
time. pointer
sk
the
function has The
this from calls start->next; a
ptr is list. it list
node If The
last
condition =
thisList
the
Displaying
oneelement.
The then process. a node, first )i
in
ptr->next the by at = start
start;
is last List functions ptr repeated
( condition list,
If
to program element
the. the
tasktask of = empty, pointed
the
first
element ptr
abOve the exiting. this
next start
This
statement
start display
this
ptr the
one
ptrand
the this forwarding
removes
are
1ast
last is repeatsRemoving main)
the (
this structure of
The list. the list structure
hefore Before deleting
ddress
start Iree steps
then
f Ta he and the These
and

You might also like