Professional Documents
Culture Documents
C Language Notes
C Language Notes
=
+ +
+ +
7oBr program shoBld De Critten so that it accepts a nBmDer of optional command line argBments
as folloCs
progname \soBrcebfile] \ destinationbfile]
(f no command line argBments are present the program shoBld read its inpBt from stdinI the
keyDoard and Crite the resBlts to stdoBtI the monitor'
(f one command line argBment is present it means that the program is to take its inpBt from the file
specified if possiDle Chere it is arranged as folloCs
!" !$ "
"& 8 =
and Crite the resBlts to the standard oBtpBt'
/astly if tCo argBments are given the program is to read its inpBt from the specified file and Crite
the resBlts to the specified destination file'
(n all cases yoBr program is to continBe reading inpBt from the inpBt device in JBestion Bntil an
-OF is encoBntered ; or Bntil a conversion error occBrs <' *ote that -OF may De prodBced at the
keyDoard Dy CtrlHa'
No05 / 7oB may not Bse any of the folloCing family of fBnctions in yoBr program for any reason
Bnless yoB implement yoBr oCn versions of them'
atoi; <I atol; <I itoa; <I ltoa; <I etc'
File (#O is not covered Bntil Chapter ? so this section shoBld De pBt aside Bntil later'
=?
" !" 6 Rem $
" 6 3 Rem $
" 3 ! Rem !
Rem !
=
=
=
= " ! $
!1 Programming A33ignm5n0 / Ta8u6a0ion Program1
7oBr main task in this assignment is to Crite and test a fBnction
in0 F0a8u6a05H in0 Fda0a, in0 num7a63 I G
+his fBnction takes as its parameters a pointer to an array of integers and the nBmDer of integers in
this array and shoBld taDBlate the valBes in the array storing the resBlts in a second array and
retBrning it as the fBnctions retBrn valBe'
7oBr main program is to first read in a Bser specified nBmDer of integers from the keyDoard and
store them in a dynamically allocated array and then call the taDBlate fBnction'
+he taDBlate fBnction mBst first determine the range of the data Deing passed to it i'e' the
maEimBm and minimBm valBes it contains and then allocate a Dlock of memory covering this
range' For eEample if the data set Cas L 6I !$I 6I ?I = M then min X 6 and maE X !$ so Ce need
to allocate a Dlock of ; maE min H ! < X 8 integers to contain all valBes in the range' +he first
element in the array is for the valBe 6I the second for =I etc'
0e also need to store the maE and min range valBes Chich tells Bs hoC many data valBes are in
the array' +o do this Ce modify the aDove representation so that Ce allocate tCo eEtra elements
to store the range' +he first element in the array is deemed to De for the minimBmI the second
for the maEimBm and the remainder for the data as Defore'
+his neC Dlock of data is neEt initialised to Pero i'e' no instances of any of the valBes in the
range are present in the data' +he data CoBld look as folloCs Cith oBr aDove eEample'
min maE > 6Os > =Os > ?Os > %Os > !$Os
6 !$ $ $ $ $ $
+he fBnction shoBld noC look at the data set and increment the coBnt associated Cith all the
elements in it appropriately' +he data set shoBld noC look like the folloCing and Cill De
retBrned to the main program Chere the resBlts Cill De displayed'
min maE > 6Os > =Os > ?Os > %Os > !$Os
6 !$ " ! ! $ !
7oBr program is also reJBired to accept one eEtra command line argBment' (f this can De
opened as a file the resBlts of the taDBlation are to De printed to it otherCise they are to De
printed to stdoBt'
=%
&1 Programming A33ignm5n0 / Po64nomia6 Par35r
The basic re)uirement of this assignment is to write a * program which can
resolve a simple polynomial into a vector of its components and to make use
of this form to implement di+erentiation of the e)uation.
The e)uation parser should be implemented as a function which is passed an
,-*"" character string which is used to represent a polynomial of degree n
which has the general form
a # a # a # a a # a # a # a #
n
n
n
n
n
n
n
n
+
+
+ + + + + + +
!
!
!
!
$ ! "
"
!
!
where ! is the dependant variable. a
n
are the coe/cients of the polynomial
&which may be limited to signed integer values(.
The character string representation may be of any degree. n. and the
components may be in any random order and may even be repeated. 0se
the 123 character to represent to the power of. The character string may also
include white space characters for readability. namely the space character.
which do not convey any information but which nonetheless must be
processed being part of the string. -ome e!amples of valid e)uations are
given below where 4 represents the space character.
1 5 ! 5 #!2# 5 6!27
#!27 5 %! 81#
89 5 #!2% 8 #! 5 7 8 !
87 !28# 5 !2815 #!2%
!424#454#4!424%
The e)uation parser must resolve the polynomial into a vector
representation. ie. it must establish a value for the coe/cient of each
component of the polynomial. This information or vector should be stored in
a single dimension integer array where the inde! into the array represents a
specifc component of the vector. :ector;0< represents the coe/cient of !20.
:ector;1< represents the coe/cient of !21. and so on up to the degree of the
polynomial.
The si=e of the vector array should be >ust su/cient to store the re)uired
vector. memory being allocated dynamically once the degree of the
polynomial has been established. ?or e!ample a polynomial of degree #
would re)uire an array of three elements to store all the component
coe/cients.
?or testing purposes your program should frst of all take in a polynomial in
the form of a character string as input. resolve this into a vector using the
parser function. and then pass this vector to a function which should
di+erentiate the vector & or e)uation ( and store the result in a di+erent
vector of appropriate dimension.
The results of each operation should be displayed in tabular form as
illustrated in the following e!ample where the e)uation input was 6!2% 5
%!2# 8 ! 5 7.
*oe/cients : !20 !21 !2# !2%
@)uation : 7 81 % 6
?$
@)uation : 81 9 16
The results of the operation should also be stored to a user specifed te!t fle
in the same tabular form as above. "n the case where the fle specifed
already e!ists and has a number of valid entries. the new entry to be added
should be separated by a blank line from the others for readability.
?!
Chapter =
S0ruc0ur53 * Union3
,1 S0ruc0ur53
A strBctBre is a cBstomised Bserdefined data type in C' (t is Dy definition a collection of variaDles
of any type that are referenced Bnder one nameI providing a convenient means of keeping related
information together'
Som5 05rmino6og4 /?
strBctBre definition Q the template Bsed to create strBctBre variaDles'
strBctBre elements Q the memDer variaDles of the strBctBre type
&efining tructures
ynta! " 30ruc0 0ag Q
04:5 7arO G
04:5 7arO! G
111
04:5 7arOn G
R G
+he keyCord 30ruc0 tells the compiler Ce are dealing Cith a strBctBre and mBst De present
Chenever Ce refer to the neC typeI 0ag is an identifier Chich is the name given to the cBstomised
FtypeF'
A variaDle of this neC type can noC De defined as folloCs for eEample' *ote that the keyCord
strBct has to De Bsed in conKBnction Cith oBr oCn name for the strBctBreI tag'
strBct tag variaDle U
For -Eample Q
strBct R-CORD L
int recbno U
char name\3$] U
char toCn\&$] U
char coBntry\ "$ ]
M U
strBct R-CORD person U
+he compiler Cill aBtomatically allocate enoBgh storage to accommodate all the elements' +o find
oBt hoC mBch storage is reJBired one might do the folloCing
siPe X siPeof ; person < U
or
siPe X siPeof; strBct R-CORD < U
NB / +he name of a strBctBre is not the address of the strBctBre as Cith array names'
$ccessing tructure +lements
For eEample define a compleE type strBctBre as folloCs'
?"
strBct compleE L
doBDle real U
doBDle imaginary U ## *ote that a variaDle may also De
M cplE U ## defined at strBctBre definition time
+he elements of the strBctBre are accessed Bsing the do0 o:5ra0orI 1 I as folloCs
cplE'real X !$'$ U
cplE'imag X "$'"3 U
scanf ; FRlfFI 9cplE'real < U
or if Ce Cant to access strBct R-CORD already defined
pBts; person'name < U
or character Dy character
person'name\i] X GaG U
+hBs Ce treat strBctBre elements eEactly as normal variaDles and vieC the dot operator as KBst
another appendage like the indirection operator or an array indeE'
Initialising tructures
6trBctBre elements or fields can De initialised to specific valBes as folloCs Q
strBct id L
char name\3$] U
int idbno U
M U
strBct id stBdent X L FdohnFI &863 M U
tructure $ssignment
+he name of a strBctBre variaDle can De Bsed on its oCn to reference the complete strBctBre' 6o
instead of having to assign all strBctBre element valBes separatelyI a single assignment statement
may De Bsed to assign the valBes of one strBctBre to another strBctBre of the same type'
For -Eample Q
strBct L
int aI D U
M E X L!I " MI y U
y X E U ## assigns valBes of all fields in E to fields in y
Creating more Comple! tructures )ith tructures
Once again emphasising that strBctBres are KBst like any other type in C Ce can create arrays of
strBctBresI nest strBctBresI pass strBctBres as argBments to fBnctionsI etc'
For eEample Ce can nest strBctBres as folloCs creating a strBctBre employeeblog that has another
strBctBre as one of its memDers'
?3
strBct time L
int hoBr U
int min U
int sec U
M U
strBct employeeblog L
char name\3$] U
strBct time startI finish U
M employeeb! U
+o access the hoBr field of time in the variaDle employeeb! KBst apply the dot operator tCice
employeeb!'start'hoBr X % U
+ypically a company Cill need to keep track of more than one employee so that an array of
employee$log CoBld De BsefBl'
strBct employeeblog Corkers\!$$] U
+o access specific employees Ce simply indeE Bsing sJBare Draces as normalI e'g' Corkers\!$]' +o
access specific memDers of this strBctBre Ce simply apply the dot operator on top of the indeE'
Corkers\!$]'finish'hoBr X !$ U
0hen strBctBres or arrays of strBctBres are not gloDal they mBst De passed to fBnctions as
parameters sBDKect to the BsBal rBles' For eEample
fBnction!; employeeb! < U
implements a call to fBnction! Chich might De prototyped as folloCs
void fBnction!; strBct employeeblog emp < U
*ote hoCever that a fBll local copy of the strBctBre passed is made so if a large strBctBre is
involved memory the overhead to simply copy the parameter Cill De high so Ce shoBld employ call
Dy reference instead as Ce Cill see in the neEt section'
2assing an array of strBctBres to a fBnction also folloCs the normal rBles DBt note that in this case
as it is impossiDle to pass an array Dy valBe no heavy initialisation penalty is paid Ce essentially
have call Dy reference' For eEample
fBnction"; Corkers < U
passes an array of strBctBres to function' Chere the fBnction is prototyped as folloCs'
fBnction"; strBct employeeblog staff\ ] < U
?&
tructure .ointers
As Ce have said already Ce need call Dy reference calls Chich are mBch more efficient than normal
call Dy valBe calls Chen passing strBctBres as parameters' +his applies even if Ce do not intend the
fBnction to change the strBctBre argBment'
A strBctBre pointer is declared in the same Cay as any pointer for eEample
strBct address L
char name\"$] U
char street\"$] U
M U
strBct address person U
strBct address @addrbptr U
declares a pointer addrbptr to data type struct address'
+o point to the variaDle person declared aDove Ce simply Crite
addrbptr X 9person U
Chich assigns the address of person to addrbptr'
+o access the elements Bsing a pointer Ce need a neC operator called the arroC operatorI WI Chich
can De Bsed on64 Cith strBctBre pointers' For eEample
pBts; addrbptr W name < U
For -Eample Q 2rogram Bsing a strBctBre to store time valBes'
>inclBde [stdio'hW
strBct timebvar L
int hoBrsI minBtesI seconds U
M U
void display ; const strBct timebvar @ < U #@ note strBctBre pointer and const @#
void main;<
L
strBct timebvar time U
time'hoBrs X !" U
time'minBtes X $ U
time'seconds X $ U
display; 9time < U
M
void display; const strBct timebvar @t <
L
printf; FR"dQR"dUR"dNnFI t W hoBrsI t W minBtesI t W seconds < U
M
*ote that even thoBgh Ce are not changing any valBes in the strBctBre variaDle Ce still employ call
Dy reference for speed and efficiency' +o clarify this sitBation the const keyCord has Deen
employed'
&ynamic allocation of structures
+he memory allocation fBnctions may also De Bsed to allocate memory for Bser defined types sBch
as strBctBres' All malloc;< Dasically needs to knoC is hoC mBch memory to reserve'
?8
For -Eample Q
strBct coordinate L
int EI yI P U
M U
strBct coordinate @ptr U
ptr X ;strBct coordinate @ < malloc; siPeof ; strBct coordinate < < U
,1! Bi0??(i56d3
5itfields are Dased directly on strBctBres Cith the additional featBre of alloCing the programmer
to specify the siPe of each of the elements in Dits to keep storage reJBirements at a minimBm'
,oCever Ditfield elements are restricted to De of type int ; signed or Bnsigned <'
For -Eample Q
strBct clock L
Bnsigned hoBr Q 8 U
Bnsigned minBtes Q 6 U
Bnsigned seconds Q 6 U
M time U
+his time strBctBre reJBires != Dits to store the information noC so the storage reJBirement is
roBnded Bp to 3 Dytes' Using the normal strBctBre format and 3"Dit integer elements Ce CoBld
reJBire !" Dytes so Ce achieve a sBDstantial saving'
5itfields can De Bsed instead of the DitCise operators in system level programmingI for eEample
to analyse the individBal Dits of valBes read from a hardCare port Ce might define the folloCing
Ditfield'
strBct statBs L
Bnsigned Dit$ Q ! U
Bnsigned Dit! Q ! U
'''
Bnsigned Dit!8 Q ! U
M U
(f Ce are interested in Dit !8 only Ce need only do the folloCing
strBct statBs L
Bnsigned Q !8 U #@ skip over first !8 Dits Cith a FnonmemDerF @#
Bnsigned Dit!8 Q ! U
M U
+here are tCo fBrther restrictions on the Bse of Ditfields
Cannot take the address of a Ditfield variaDle
Cannot create an array of Ditfield variaDles
Can yoB sBggest reasons for this ^
,1& Union3
A Bnion is data type Chere the data area is shared Dy tCo or more memDers generally of different
type at different times'
For -Eample Q
?6
union uO0ag Q
3;or0 i7a6 G
26oa0 27a6 G
c;ar c7a6 G
R u7a6 G
+he siPe of Bval Cill De the siPe reJBired to store the largest single memDerI & Dytes in this case to
accommodate the floating point memDer'
Union memDers are accessed in the same Cay as strBctBre memDers and Bnion pointers are valid'
Bval'ival X !$ U
Bval'cval X GcG U
0hen the Bnion is accessed as a character Ce are only Bsing the Dottom Dyte of storageI Chen it is
accessed as a short integer the Dottom tCo Dytes etc' (t is Bp to the programmer to ensBre that the
element accessed contains a meaningfBl valBe'
A Bnion might De Bsed in conKBnction Cith the Ditfield struct status in the previoBs section to
implement Dinary conversions in C'
For -Eample Q
Bnion conversion L
Bnsigned short nBm U
strBct statBs Dits U
M nBmDer U
0e can load nBmDer Cith an integer
scanf; FRBFI 9nBmDer'nBm <U
6ince the integer and Ditfield elements of the Bnion share the same storage if Ce noC access the
Bnion as the Ditfield variaDle bits Ce can interpret the Dinary representation of nBm directly'
i'e' if ; Bvar'Dits'Dit!8 <
pBtchar; G!G < U
else
pBtchar;G$G< U
'''
if ; Bvar'Dits'Dit$ <
pBtchar; G!G < U
else
pBtchar;G$G< U
Admittedly rather inefficient and inelegant DBt effective'
,1' Enum5ra0ion3
?=
An enBmeration is a Bser defined data type Chose valBes consist of a set of named integer
constantsI and are Bsed for the sole pBrpose of making program code more readaDle'
ynta!" 5num 0ag Q 7a6u5O6i30 R A 5numO7ar C G
Chere tag is the name of the enBmeration typeI valBeblist is a list of valid valBes for the
enBmerationI and Chere enBmbvar is an actBal variaDle of this type'
For -Eample Q
enBm coloBrs L redI greenI DlBeI orange M shade U
## valBes red $I green !I DlBe "I orange 3
enBm day L sBn X !I monI tBeI Ced X "!I thBrI friI sat M U
enBm day Ceekday U
## valBes are !I "I 3I "!I ""I "3I "&
4ariaDles declared as enBmerated types are treated eEactly as normal variaDles in Bse and are
converted to integers in any eEpressions in Chich they are Bsed'
For -Eample Q
int i U
shade X red U ## assign a valBe to shade enBm variaDle
i X shade U ## assign valBe of enBm to an int
shade X 3 U ## assign 7a6id int to an enBmI treat Cith care
,1) T;5 04:5d52 S54Bord
C makes Bse of the 04:5d52 keyCord to alloC neC data type nam53 to De defined' *o neC type is
createdI an eEisting type Cill noC simply De recognised Dy another name as Cell' +he eEisting type
can De one of the inDBilt types or a Bserdefined type'
ynta! " 04:5d52 04:5 nam5 G
Chere type is any C data type and name is the neC name for this type'
For -Eample Q
typedef int (*+-)-R U
(*+-)-R i U ## can noC declare a variaDle of type T(*+-)-RO
typedef doBDle @ doBDlebptr U
doBDlebptr ptr U ## no need of @ here as it is part of the type
typedef strBct coords L
int EI y U
M Eycoord U ## Eycoord is noC a type name in C
Eycoord coordbvar U
+he Bse of typedef makes program code easier to read and Chen Bsed intelligently can facilitate
the porting of code to a different platform and the modification of code' For eEample in a first
attempt at a particBlar program Ce might decide that floating point variaDles Cill fill oBr needs' At
a later date Ce decide that all floating point variaDles really shoBld De of type doBDle so Ce have to
change them all' +his proDlem is trivial if Ce had Bsed a typedef as folloCs Q
typedef float F/OA+(*) U
??
+o remedy the sitBation Ce modify the Bser defined type as folloCs
typedef doBDle F/OA+(*) U
,1+ #inT5d #i303
0hen Ce have needed to represent collections of data Bp Bntil noC Ce have typically Bsed data
strBctBres sBch as arrays Chose dimensions Cere fiEed at compile time or Chich Cere dynamically
allocated as reJBired' +hese arrays coBld have Deen arrays of Dasic data typesI e'g' doBDlesI or
coBld have Deen arrays of strBctBres Chen more compleE data needed to De represented'
,oCever this method of representing dataI Chile perfectly adeJBate in many sitBationsI is limited
and can De very inefficient Chen Ce are dealing Cith sitBations Chere the data collection has to De
modified at rBntime'
For eEample if Ce are dealing Cith an ordered list of records and Ce need to insert a neC recordI
for dohn sayI in the correct position in the list Ce might have to go throBgh the folloCing steps'
!' -Epand the memory space allocated to the array to take one more record'
Alan 5en 6am +om
"' Determine the correct position in the array at Chich to insert the element e position 3'
3' Reposition the data so that the appropriate position is left BnBsed'
Alan 5en 6am +om
&' (nsert the neC element into the list'
Alan 5en dohn 6am +om
0hatever oBr internal representation of the dataI steps !I" 9 & Cill have to De carried oBt in one
form or another' ,oCever step 3 can De avoided if Ce represent the data in an alternate fashion'
(f Ce can represent oBr data as a chain of interconnected records as illBstrated DeloC Chere each
record has its oCn memory space and knoCs Chich record comes Defore and after it Ce have a
mBch more fleEiDle strBctBre'
?%
Alan #en Sam Tom
$ohn
#rea%
Existin& Lin%
'ew Lin%s
*oC Chen Ce Cant to insert a neC record in position Ce still mBst allocate the appropriate amoBnt
of memory to store it ;note in this case it is a discrete Dlock< and Ce still mBst figBre oBt Chich
position it Delongs in DBt Ce no longer have to manipBlate the position of the other records in
memory' +hese Cill noC stay eEactly Chere they are DBt Ce Cill have to inform the records Defore
and after the position at Chich Ce Cish to insert that they Cill De pointing to a different record'
Using the normal terminology Ce say Ce have a list of nodes linked together Dy pointer links' +o
insert a neC item into the list Ce Dreak an eEisting link and create tCo neC links incorporating the
neC node into the list'
Nodes or elf#'eferential tructures
A strBctBre that contains a pointer memDer that points to a strBctBre of the same type as itself is
said to De a selfreferential strBctBre' For eEample Q
strBct node L
char name\"$] U
strBct node @neEtnode U
MU
+his defines a neC typeI 30ruc0 nod5I Chich has a pointer memDerI ne#tnode, Chich points to a
strBctBre of the same type as itself' +his node pointer alloCs this cBrrent node to De linked to
another and so a list of linked nodes can De DBilt Bp'
*ote that even thoBgh the strBctBre is not fBlly defined Chen the ne#tnode field is specified the
compiler does not have a proDlem as all it needs to knoC is that there is sBch a type'
+he aDove definition of strBct node alloCs Bs to DBild a singly linked list i'e' each node only knoCs
Chere the node folloCing it is located' A nBll pointer is Bsed to indicate the end of a linked list
strBctBre'
+he diagram DeloC illBstrates hoC this node strBctBre CoBld De Bsed to represent oBr linked list
aDove' -ach node contains tCo fields the actBal data and a pointer link to the neEt node' +he final
node in the list contains a nBll pointer link as indicated Dy the slash in the diagram'
Alan #en Sam Tom
Connecting the Nodes
%$
+he Dasic DBilding Dlock in a linked list is KBst a C strBctBre so Ce can initialise it in the same Cay
as any other strBctBre' For eEample in oBr aDove sitBation to allocate and initialise the first node
Ce might do the folloCing Q
strBct node @nodeb! U
nodeb! X ; strBct node @<malloc; siPeof ; strBct node < < U
strcpy; nodeb!WnameI .Alan1 < U
nodeb!WneEtnode X *U// U
+his Dlock of code initialises this node only and DecaBse the ne#tnode pointer is assigned a nBll
pointer valBe it designates it as the final ;and only< node in the list'
(f Ce Cant to add on an item to the list Ce can do the folloCing Q
strBct node @nodeb" U
nodeb" X ; strBct node @<malloc; siPeof ; strBct node < < U
strcpy; nodeb"WnameI .5en1 < U
nodeb"WneEtnode X *U// U
nodeb!WneEtnode X nodeb" U
*ote that it is only the last line of code that adds the item onto the list' +he remaining code KBst
allocates storage and initialises a neC node as Defore'
0e noC have a linked list Cith tCo nodes' +he node pointer node$( points to the first element in
the list Chich is normally called the list ;5ad' As all the nodes in the list are connected via their
link pointer this is in fact a pointer to the complete linked list so Ce CoBldnOt need to store nodeb"I
etc' at all' +he last node has a nBll pointer Chich identifies it as the last node in the linked list and
is called the list 0ai6'
%perations on (in/ed (ists
0hen Corking Cith linked lists Ce Cill need to perform a nBmDer of operations JBite often so it
makes sense to DBild Bp a liDrary of these at the oBtset' 0e Cill need to De aDle to insert items into
the listI remove items from the listI traverse the listI etc'
0e Cill continBe to Bse oBr definition of a node eEcept that Ce Cill typedef it as folloCs Q
typedef strBct node L
char name\"$] U
strBct node @neEtnode U
M listbnode U
*ote in this case Ce cannot Bse the typedef name to declare neEtnode as this name is not in
eEistence at that point'
+o declare the linked list Ce simply declare a pointer to one of these strBctBre types'
listbnode @ptrbhead X *U// U
Tra,ersing a (ist
(n many list operations Ce Cill need to process the information in each nodeI for eEample to print
the complete information in the listU this is termed tra!ersing a list.
An iterative version of a print$list fBnction might De as folloCs Q
%!
void printblist; listbnode @pbhead <
L
listbnode @nodebptr U
for ; nodebptr X pbhead U nodebptr SX *U// U nodebptr X nodebptrWneEtnode <
pBts; nodebptrWname < U
M
Chereas a recBrsive version might De implemented as folloCs Q
void printblist; listbnode @pbhead <
L
if ; pbhead XX *U// <
pBts;.Nn1 <U
else
L
pBts; pbheadWname < U
printblist; pbheadWneEtnode < U
M
M
Inserting a Node
+here are a variety of Cays this fBnction can De implemented inserting a node in the correct
orderI at the headI at the tailI Dy positionI etc' For oBr eEample Ce Cill Crite a fBnction to insert a
neC node in the correct order assBming the node has Deen fBlly created Defore Deing passed to Bs'
void insert; listbnode @@pbheadI listbnode @neC <
L
listbnode @nodebptr X @pbhead U
listbnode @prev X *U// U
Chile ; nodebptr SX *U// 99 ;strcmp; neCWnameI nodebptrWname < W $ < <
L
prev X nodebptr U
nodebptr X nodebptrWneEtnode U
M
if ; prev XX *U// < ## head position
L
neCWneEtnode X @pbhead U
@pbhead X neC U
M
else
L
prevWneEtnode X neC U
neCWneEtnode X nodebptr U
M
M
'emo,ing a Node
0e Cill implement this as a fBnction Chich finds the node Dy the name fieldI Bnlinks it from the list
and retBrns a pointer to the removed node CithoBt freeing its associated memory'
listbnode @delete; listbnode @@pbheadI char @name <
L
listbnode @prev X *U//I @cBrrI @nodebptr X @pbhead U
Chile ; nodebptr SX *U// 99 strcmp; nameI nodebptrWname < <
L
%"
prev X nodebptr U
nodebptr X nodebptrWneEtnode U
M
if ; prev XX *U// < ## removing head position
L
@pbhead X ;@pbhead<WneEtnode U
retBrn nodebptr U
M
else L
prevWneEtnode X nodebptrWneEtnode U
retBrn nodebptr U
M
M
*ote the Bse of doBDle indirection to type list$node in each of the aDove fBnctions' Can yoB
eEplain Chy this is necessary ^
+he folloCing main fBnction is a trivial illBstration of hoC to Bse the aDove fBnctions in practice'
void main()
{
list=node *ptr=head 1 V>?? '
struct node *node=0/ *node=3 '
node=0 1 ( struct node *)malloc( siGeo ( struct node ) ) '
strcp+( node=08>name/ #Ulan# ) '
insert( Eptr=head/ node=0 ) '
node=3 1 ( struct node *)malloc( siGeo ( struct node ) ) '
strcp+( node=38>name/ #\en# ) '
insert( Eptr=head/ node=3) '
puts( )?ist with Ulan E \en,) '
print=list( ptr=head ) '
delete( Eptr=head/ #\en# ) '
puts( )?ist with Ulan,) '
print=list( ptr=head ) '
(
0hat Ce have discBssed in the eEample aDove is one of the more general variations of a linked list'
Many different implementations can De implemented Cith slightly different fBnctionality for
eEample Ce can implement doBDly linked listsI stacks ;/(FO< or JBeBes ;F(FO< Bsing the same
Dasic DBilding Dlocks'
%3
,1, E22ici5nc4 Con3id5ra0ion3
As descriDed previoBsly pointers shoBld De Bsed to implement callDyreference in passing large
Bser defined data items to fBnctions to redBce the copying overhead involved in callDyvalBe' (f
implementing a typical callDyvalBe sitBation Bse of the const keyCord can protect Bs from
inadvertent modification of the referenced argBment'
Care shoBld De taken not to go overDoard in defining large complicated data strBctBres CithoBt
need and to Bse them appropriately'
For eEample Chen dealing Cith lists of data of any type a normal array may sometimes De a Detter
choice as a data strBctBre rather than a linked list' +he Dig advantage a linked list has over a linear
array is that yoB can insert or delete items at Cill CithoBt shifting the remaining data'
,oCever the eEtra overhead involved in setting Bp the linked listI Doth the calls to malloc;< to
allocate each neC element and the TeEtraO pointer associated Cith each elementI may not KBstify its
selection'
6Bppose Ce need to keep a list of integers' +hen most of the storage is taken Bp Cith the eEtra
pointer information Bsed solely for maintaining the list ; the pointer to the neEt element and the
pointer to each integer <'
%&
,1- E95rci353
1 0rite a program Chich Cill simBlate the action of a digital clock continBoBsly as closely as
possiDle' Use a strBctBre to hold the valBes of hoBrsI minBtes and seconds reJBired' 7oBr program
shoBld inclBde a fBnction to display the cBrrent time and to Bpdate the time appropriately Bsing a
delay fBnction#loop to simBlate real time reasonaDly Cell' 2ointers to the clock strBctBre shoBld De
passed to the display and Bpdate fBnctions rather than Bsing gloDal variaDles'
!1 CompleE nBmDers are not sBpported as a distinct type in C DBt are BsBally implemented Dy
individBal Bsers as Bser defined strBctBres Cith a set of fBnctions representing the operations
possiDle on them' Define a data type for compleE valBes and provide fBnctions to sBpport additionI
sBDtractionI mBltiplication and division of these nBmDers' Use call Dy reference to make these
fBnctions as efficient as possiDle and try to make their Bse as intBitive as yoB can'
&1 0rite a program Chich Cill
;a< set Bp an array of strBctBres Chich Cill hold the namesI dates of DirthI and addresses of
a nBmDer of employees'
;D< assign valBes to the strBctBre from the keyDoard'
;c< sort the strBctBres into alphaDetical order Dy name Bsing a simple DBDDle sort
algorithm'
;d< print oBt the contents of a specific array element on demand'
'1 Use a comDination of Ditfields and Bnions in C to print oBt the Dit patterns of any Bnsigned
integer valBes inpBt at the keyDoard'
)1 5CD ;5inary Coded Decimal< codes are commonly Bsed in indBstrial applications to represent
decimal nBmDers' ,ere foBr Dits are Bsed to represent each decimal digit I e'g'
5555 11> 5
5550 11> 0
...
0550 11> @
+hBs short int can De Bsed to represent a foBr digit decimal nBmDer'
Use 5itFields to implement conversion roBtines to encode a decimal nBmDer into 5CD format
and Dack again'
+1 Redo proDlem ! Bsing a Ditfield strBctBre as an illBstration of hoC memory reJBirements may
De redBced' Compare the old and neC memory reJBirements for data storage'
,1 Using a doBDly linked list data strBctBre Crite a program that maintains an alphaDetically
ordered list of stBdent registration records' +he information held in each record shoBld inclBde the
stBdentOs nameI stBdent identity nBmDerI addressI coBrseI etc' 7oBr program shoBld alloC the Bser
to add on records to the listI to remove records from the listI to amend records and to prodBce a
screen dBmp of all records' Use distinct fBnctions for all maKor operations if possiDle'
-1 Use a F(FO implementation of a linked list to represent a JBeBe of people entered Dy the Bser'
%8
Chapter ?
S0andard (i65 I%O
+he C standard liDrary (#O fBnctions alloC yoB to read and Crite data to Doth files and devices'
+here are no predefined file strBctBres in CI all data Deing treated as a seJBence of Dytes' +hese
(#O fBnctions may De Droken into tCo different categories Q stream (#O and loClevel (#O'
+he stream (#O fBnctions treat a data file as a stream of individBal characters' +he appropriate
stream fBnction can provide DBfferedI formatted or Bnformatted inpBt and oBtpBt of dataI ranging
from single characters to complicated strBctBres' 5Bffering streamlines the (#O process Dy
providing temporary storage for data Chich takes aCay the DBrden from the system of Criting each
item of data directly and instead alloCs the DBffer to fill Defore caBsing the data to De Critten'
+he loClevel (#O system on the other hand does not perform any DBffering or formatting of data
instead it makes direct Bse of the systemGs (#O capaDilities to transfer BsBally large Dlocks of
information'
-1 S0r5am I%O
+he C (#O system provides a consistent interface to the programmer independent of the actBal
device Deing accessed' +his interface is termed a 30r5am in C and the actBal device is termed a 2i65'
A device may De a disk or tape driveI the screenI printer portI etc' DBt this does not Dother the
programmer DecaBse the stream interface is designed to De largely device independent' All (#O
throBgh the keyDoard and screen that Ce have seen so far is in fact done throBgh special standard
streams called 30din and 30dou0 for inpBt and oBtpBt respectively' 6o in essence the console
fBnctions that Ce have Bsed so far sBch as printf;<I etc' are special case versions of the file
fBnctions Ce Cill noC discBss'
+here are tCo types of streams Q teEt and Dinary' +hese streams are Dasically the same in that all
types of data can De transferred throBgh them hoCever there is one important difference DetCeen
them as Ce Cill see'
Te!t treams
A teEt stream is simply a seJBence of characters' ,oCever the characters in the stream are open to
translation or interpretation Dy the host environment' For eEample the neCline characterI GNnGI Cill
normally De converted into a carriage retBrn#linefeed pair and Ya Cill De interpreted as -OF' +hBs
the nBmDer of characters sent may not eJBal the nBmDer of characters received'
Binary treams
A Dinary stream is a seJBence of data comprised of Dytes that Cill not De interfered Cith so that a
onetoone relationship is maintained DetCeen data sent and data received'
%6
Common 5ile 5unctions
open() open a stream
close() close a stream
putc()E putc() Crite a character to a stream
"etc()E "etc() read a character from a stream
print()E scan formatted (#O
"ets() E puts() string handling
seek() position the file pointer at a particBlar Dyte
eo() tests if -OF
%pening and Closing 5iles
A stream is associated Cith a specific file Dy performing an open operation' Once a file is opened
information may De eEchanged DetCeen it and yoBr program' -ach file that is opened has a BniJBe
file control strBctBre of type F(/- ; Chich is defined in [stdio'hW along Cith the prototypes for all
(#O fBnctions and constants sBch as -OF ;!< <' A 2i65 :oin05r is a pointer to this F(/- strBctBre
Chich identifies a specific file and defines varioBs things aDoBt the file inclBding its nameI
read#Crite statBsI and cBrrent position' A file pointer variaDle is defined as folloCs
XS?< *ptr '
+he fopen;< fBnction opens a stream for Bse and links a file Cith that stream retBrning a valid file
pointer Chich is positioned correctly Cithin the file if all is correct' fopen;< has the folloCing
prototype
XS?< *open( const char *ilename/ const char
*mode )'
Chere filename is a pointer to a string of characters Chich make Bp the name and path of the
reJBired fileI and mode is a pointer to a string Chich specifies hoC the file is to De opened' +he
folloCing taDle lists some valBes for mode'
r opens a teEt file for reading ;mBst eEist<
C opens a teEt file for Criting ;overCritten or created<
a append to a teEt file
rD opens a Dinary file for reading
CD opens a Dinary file for Criting
aD appends to a Dinary file
rH opens a teEt file for read#Crite ;mBst eEist<
CH opens a teEt file for read#Crite
aH append a teEt file for read#Crite
rDH opens a Dinary file for read#Crite
CDH opens a Dinary file for read#Crite
aDH append a Dinary file for read#Crite
(f open( ) cannot open Ftest.dat F it Cill a retBrn a *U// pointer Chich shoBld alCays
De tested for as folloCs'
XS?< *p '
i ( ( p 1 open( #test.dat#/ #r# ) ) 11 V>?? )
{
puts( #Cannot open ile#) '
e!it( 0) '
(
+his Cill caBse the program to De eEited immediately if the file cannot De opened'
+he close() fBnction is Bsed to disassociate a file from a stream and free the stream for Bse
again'
%=
close( p ) '
close() Cill aBtomatically flBsh any data remaining in the data DBffers to the file'
'eading * Writing Characters
Once a file pointer has Deen linked to a file Ce can Crite characters to it Bsing the putc()
fBnction'
putc( ch/ p ) '
(f sBccessfBl the fBnction retBrns the character Critten otherCise -OF' Characters may De read
from a file Bsing the fgetc;< standard liDrary fBnction'
ch 1 "etc( p ) '
0hen -OF is reached in the file "etc( ) retBrns the -OF character Chich informs Bs to stop
reading as there is nothing more left in the file'
For -Eample Q 2rogram to copy a file Dyte Dy Dyte
#include <stdio.h>
void main()
{
XS?< *in/ *out '
char dest]45^/ source]45^/ ch '
puts( #<nter source ile name# )'
"ets( source )'
puts( #<nter destination ile name# )'
"ets( dest ) '
i ( ( in 1 open( source/ #rb# ) ) 11 V>?? ) //
open as binar+ as we donPt
{// know what is in ile
puts( #Cannot open input ile #) '
puts( source ) '
e!it( 0 ) '
(
i ( ( out 1 open( dest/ #wb# ) ) 11 V>?? )
{
puts( #Cannot open output ile #) '
puts( dest ) '
e!it( 0 ) '
(
while ( ( ch 1 "etc( in ) ) H1 <DX )
putc( ch / out ) '
close( in ) '
close( out ) '
(
NB / 0hen any stream (#O fBnction sBch as fgetc;< is called the cBrrent position of the file pointer
is aBtomatically moved on Dy the appropriate amoBntI ! character# Dyte in the case of fgetc;< U
%?
Wor/ing )ith strings of te!t
+his is JBite similar to Corking Cith characters eEcept that Ce Bse the fBnctions "ets() and
puts() Chose prototypes are as folloCs Q
int puts( const char *str/ XS?< *p ) '
char *"ets( char *str/ int ma!len/ XS?< *p ) '
For -Eample Q 2rogram to read lines of teEt from the keyDoardI Crite them to a file and then read
them Dack again'
#include <stdio.h>
void main()
{
char ile]F5^/ strin"]F5^ '
XS?< *p '
print( #<nter ile Vame * # )'
"ets( ile )'
i (( p 1 open( ile/ #w# )) 11 V>?? )//open or
writin"
{
print( #Cannot open ile As#/ ile ) '
e!it( 0 ) '
(
while ( strlen ( "ets( str ) ) > 5 )
{
puts( str/ p ) '
putc( 2&n2/ p ) ' /* must append &n or
readabilit+ 88 not stored b+ "ets() */
(
close( p ) '
i (( p 1 open( ile/ #r# )) 11 V>?? )//open or
readin"
{
print( #Cannot open ile As#/ ile ) '
e!it( 0 ) '
(
while ("ets( str/ 7@/ ptr ) H1 <DX )// read at most 7@
characters
puts( str ) '
close( p ) '
(
%%
5ormatted I6%
For -Eample Q 2rogram to read in a string and an integer from the keyDoardI Crite them to a disk
file and then read and display the file contents on screen'
#include <stdio.h>
#include <stdlib.h>
void main()
{
XS?< *p '
char s]F5^ '
int t '
i ( ( p 1 open( #test.dat#/ #w# ) ) 11 V>?? )
{
puts( #Cannot open ile test.dat#) '
e!it(0) '
(
puts( #<nter a strin" and a number#) '
scan( #As Ad#/ s/ Et )'
print( p/ #As Ad#/ s/ t )'
close( p ) '
i ( ( p 1 open( #test.dat#/ #r# ) ) 11 V>?? )
{
puts) #Cannot open ile#) '
e!it(0) '
(
scan( p/ #As Ad# / s / Et ) '
print( #As/ Ad&n#/ s/ t ) '
close( p ) '
(
No05 / +here are several (#O streams opened aBtomatically at the start of every C program'
stdin standard inpBt ie' keyDoard
stdout standard oBtpBt ie' screen
stderr again the screen for Bse if stdoBt malfBnctions
(t is throBgh these streams that the console fBnctions Ce normally Bse operate' For eEample in
reality a normal printf call sBch as
print( #As Ad#/ s/ t ) '
is in fact interpreted as
print( stdout/ #As Ad#/ s/ t ) '
fread() and f)rite()
!$$
+hese tCo fBnctions are Bsed to read and Crite Dlocks of data of any type' +heir prototypes are as
folloCs Chere siPebt is eJBivalent to Bnsigned'
siGe=t read( void *buer/ siGe=t num=b+tes/ siGe=t count/
XS?< *p ) '
siGe=t write( const void *buer/ siGe=t num=b+tes/ siGe=t
count/ XS?< *p ) '
Chere 8u225r is a pointer to the region in memory from Chich the data is to De read or Critten
respectivelyI numO84053 is the nBmDer of Dytes in each item to De read or CrittenI and coun0 is the
total nBmDer of items ; each nBmbDytes long < to De read#Critten' +he fBnctions retBrn the nBmDer
of items sBccessfBlly read or Critten'
For -Eample Q
#include <stdio.h>
#include <stdlib.h>
struct ta" {
loat balance '
char name] F5 ^ '
( customer 1 { 034.343/ #`ohn# ( '
void main()
{
XS?< *p '
double d 1 03.4: '
int i]:^ 1 {05 / 35/ 45/ :5 ( '
i ( (p 1 open ( #test.dat#/ #wbB# ) ) 11 V>?? )
{
puts( #Cannot open Xile# ) '
e!it(0) '
(
write( Ed/ siGeo( double )/ 0/ p ) '
write( i/ siGeo( int )/ :/ p ) '
write( Ecustomer/ siGeo( struct ta" )/ 0/ p ) '
rewind( p ) ' /* repositions ile pointer to start */
read( Ed/ siGeo( double )/ 0/ p ) '
read( i/ siGeo( int )/ :/ p ) '
read( Ecustomer/ siGeo( struct ta" )/ 0/ p ) '
close( p ) '
(
NB / Unlike all the other fBnctions Ce have encoBntered so far fread and fCrite read and Crite
8inar4 data in the same format as it is stored in memory so if Ce try to edit one these files it Cill
appear completely garDled' FBnctions like fprintfI fgetsI etc' read and Crite displayaDle data'
fprintf Cill Crite a doBDle as a series of digits Chile fCrite Cill transfer the contents of the ? Dytes
of memory Chere the doBDle is stored directly'
'andom $ccess I6%
!$!
+he seek() fBnction is Bsed in C to perform random access (#O and has the folloCing
prototype'
int seek ( XS?< *p/ lon" num=b+tes/ int ori"in ) '
Chere origin specifies one of the folloCing positions as the origin in the operation
6--Ab6-+ Deginning of file
6--AbCUR cBrrent position
6--Ab-*D -OF
and Chere numO84053 is the offset in Dytes to the reJBired position in the file' fseek;< retBrns Pero
Chen sBccessfBlI otherCise a nonPero valBe'
For -Eample if Ce had opened a file Chich stored an array of integers and Ce Cish to read the
8$
th
valBe Ce might do the folloCing
seek ( p/ ( :@ * siGeo( int ) )/ M<<T=M<T ) '
scan( p/ #Ad#/ Ei ) '
from anyChere in the program'
-1! #oB ?? #5756 I%O
/oC level file inpBt and oBtpBt in C does not perform any formatting or DBffering of data
ChatsoeverI transferring Dlocks of anonymoBs data instead Dy making Bse of the Bnderlying
operating systemGs capaDilities'
/oC level (#O makes Bse of a file handle or descriptorI Chich is KBst a nonnegative integerI to
BniJBely identify a file instead of Bsing a pointer to the F(/- strBctBre as in the case of stream (#O'
As in the case of stream (#O a nBmDer of standard files are opened aBtomatically Q
30andard in:u0 ??? E
30andard ou0:u0 ???
30andard 5rror ??? !
+he folloCing taDle lists some of the more common loC level (#O fBnctionsI Chose prototypes are
given in [io'hW and some associated constants are contained in [fcntl'hW and [sysNstat'hW'
open;< opens a disk file
close;< closes a disk file
read;< reads a DBffer of data from
disk
Crite;< Crites a DBffer of data to disk
+he open fBnction has the folloCing prototype and retBrns ! if the open operation fails'
int open ( char *ilename/ int ola" ]/ int pmode^ ) '
Chere filename is the name of the file to De openedI oflag specifies the type of operations that are
to De alloCed on the fileI and pmode specifies hoC a file is to De created if it does not eEist'
o26ag may De any logical comDination of the folloCing constants Chich are KBst bit flags comDined
Bsing the DitCise OR operator'
!$"
ObA22-*D appends to end of file
Ob5(*AR7 Dinary mode
ObCR-A+ creates a neC file if it doesnGt eEist
ObRDO*/7 read only access
ObRD0R read Crite access
Ob+-:+ teEt mode
Ob+RU*C trBncates file to Pero length
Ob0RO*/7 Crite only access
:mod5 is only Bsed Chen ObCR-A+ is specified as part of oflag and may De one of the folloCing
valBes
SOI=RITE
SOIREAD
SOIREAD U SOI=RITE
+his Cill actBally set the read # Crite access permission of the file at the operating system level
permanently Bnlike oflag Chich specifies read # Crite access KBst Chile yoBr program Bses the file'
+he close() fBnction has the folloCing prototype
int close ( int handle ) '
and closes the file associated Cith the specific handle'
+he read() and write() fBnctions have the folloCing prototypes
int read( int handle/ void *buer/ unsi"ned int count ) '
int write( int handle/ void *buer/ unsi"ned int
count ) '
Chere handle refers to a specific file opened Cith open;<I DBffer is the storage location for the data
; of any type < and coBnt is the maEimBm nBmDer of Dytes to De read in the case of read;< or the
maEimBm nBmDer of Dytes Critten in the case of Crite;<' +he fBnction retBrns the nBmDer of Dytes
actBally read or Critten or ! if an error occBrred dBring the operation'
-Eample Q 2rogram to read the first !$$$ characters from a file and copy them to another'
#include <io.h>
#include <cntl.h>
#include <s+s&stat.h>
void main()
{
char bu]0555^ '
int handle '
handle1open(# test.dat#/ D=\SVUYQJD=YLDV?Q/ M=SY<UL J
M=S%YST< )'
i ( handle 11 80 ) return '
i ( read( handle/ bu/ 0555 ) 11 0555 )
puts( #Yead successul#)'
else
{
puts( Yead ailed# ) '
e!it( 0 )'
(
!$3
close( handle ) '
handle 1 open(#test.bak#/
D=\SVUYQJD=CY<UTJD=%YDV?QJ D=TY>VC/
M=SY<UL J M=S%YST< ) '
i ( write( handle/ bu/ 0555 ) 11 0555 )
puts( #%rite successul#) '
else
{
puts( #%rite Xailed#) '
e!it( 0 ) '
(
close( handle ) '
(
/oC level file (#O also provides a seek fBnction 6355T Cith the folloCing prototype'
lon" =lseek( int handle/ lon" offset/ int origin )'
O6355T Bses the same origin etc' as fseek() DBt Bnlike fseek;< retBrns the offsetI in DytesI of the neC
file position from the Deginning of the file or ! if an error occBrs'
For -Eample Q 2rogram to determine the siPe in Dytes of a file'
#include <stdio.h>
#include <io.h>
#include <cntl.h>
#include <s+s&stat.h>
void main()
{
int handle '
lon" len"th '
char name]F5^ '
print( )<nter ile name * , ) '
"ets( name ) '
handle1open( name/D=\SVUYQJ D=YLDV?Q/ M=SY<UL J
M=S%YST< )'
lseek( handle/ 5?/ M<<T=M<T ) '
len"th 1 lseek( handle/ 5?/ M<<T=<VL ) '
close( handle ) '
print( )The len"th o As is Ald b+tes &n,/ name/ len"th )
'
(
-1& E95rci353
1 0rite a program that determines the folloCing statistics pertaining to a teEt file'
i' +otal nBmDer of characters
ii' *BmDer of alphaDetic characters
iii' *BmDer of Cords
!$&
iv' *BmDer of non alphaDetic characters
v' +aDBlates the Bsage of each letter of the alphaDet'
!1 0rite a program that compBtes the valBe of 6in; E < for E in the range $ to " in steps of $'$!
radians and stores them in a Dinary file' +his lookBp taDle is commonly Bsed to improve program
performance in practical programming rather than calcBlating valBes on the spot' Using the
standard liDrary random nBmDer generator to generate the angles compare the time it takes to
TcalcBlateO 6in;E< for !$$ valBes of E Bsing the lookBp taDle and calcBlating them straight' 7oB
might find the standard liDrary time fBnctions BsefBl to compare times accBrately'
&1 Programming A33ignm5n0 / Sim:65 Da0aBa351
0rite a simple dataDase program Chich stores and manages information of the type contained in
the folloCing strBctBre Dy making Bse of a dynamically allocated array # list of strBctBres of this
type as descriDed DeloC'
t+pede struct details {
int rec=id '
char name]35^ '
char address]F5^ '
lon" >CCid '
( L<TUS?M '
t+pede struct list {
L<TUS?M **data=items '
int numrecords '
int selrecord '
( ?SMT '
+he list strBctBre defined aDove contains three data items' [nBmrecordsW is the total nBmDer of
records in the list at presentI [selrecordW is the cBrrent record selectedI and [databitemsW is a
pointer to a pointer to type D-+A(/6I i'e' a doBDly indirected pointer to the actBal data'
+he data is arranged as illBstrated DeloC in the case of a list Cith tCo records'
+he list strBctBre tells Bs that there are tCo records in the listI the cBrrent Deing the first in the list'
+he pointer mylistWdatabitemsI of type D-+A(/6 @@I has Deen allocated memory to store tCo
addressesI of type D-+A(/6 @I i'e' the addresses for each individBal record' -ach of these
individBal pointersI i'e' @;mylistWdatabitems H i<I has Deen allocated sBfficient memory to store an
individBal record'
7oBr program shoBld set Bp a data strBctBre of the type descriDed aDove and alloC the Bser to
perform the folloCing tasks'
!$8
!' Add a record to the dataDase'
"' 6earch for a record Dy field in the dataDase'
3' Order the dataDase Dy field'
&' Retrieve a record from the dataDase'
8' -Etract a record from the dataDaseI deleting it completely'
6' 6ave the dataDase appropriately to a file'
=' /oad an eEisting dataDase from a file'
7oBr program shoBld contain the folloCing fBnctions # featBres'
void initlist( ?SMT *list ) '
+his fBnction shoBld set [selrecordW X [nBmrecordsW X $ and [databitemsW X *U//'
void add( ?SMT *list/ L<TUS?M *new )'
+his fBnction shoBld add the record pointed to Dy [neCW onto the end of the list pointed to Dy
[listW' +his means that [selrecordW and [nBmrecordsW Cill have to De modified appropriately and
the pointer
[listWdatabitemsW mBst De resiPed to hold the address of one eEtra record ; Bsing realloc( )
for eEample <I and memory mBst De allocated for the actBal record i'e' or *( list8>
data=items B list8>numrecords 8 0 )'
L<TUS?M *probe( ?SMT *list/ int i ) '
+his fBnction retBrns a pointer to the cBrrent record and aBtomatically moves yoB onto the neEt
record' (f the cBrrent selection is $I i'e' no record eEists in the listI the fBnction shoBld retBrn
*U//' (f the cBrrent selection is otherCise invalid [selrecordW shoBld De reset to the first record
and continBe as normal' (f [iW is eJBal to Pero the list is to De reset and continBe as normalI
otherCise ignore [iW'
void e!tract( ?SMT *list )'
+his fBnction removes the cBrrent selection completely from the list' (t removes nothing if the
cBrrent record is invalid'
void swap( ?SMT *list/ int i/ int . ) '
6Caps records i and K in the list' *ote yoB shoBld only sCap the actBal addresses of the individBal
records'
void orderlist( ?SMT *list/ int ield ) '
+his fBnction shoBld ideally order the complete list in terms of the field givenI e'g' in terms of
nameI UCCidI etc' ,oCever it Cill sBffice to do this in terms of name only say'
L<TUS?M *search( ?SMT *list/ char *item/ int ield ) '
6earch the list from the cBrrent position onI for the neEt occBrrence of the searchitemI [itemWI in a
particBlar field of the list ; Cith the same proviso as aDove <' +he fBnction retBrns the nBll pointer
if the item is not foBndI or a pointer to the particBlar record if it is foBnd' +he record Decomes the
cBrrent selection'
A22-*D(: A Q A6C(( Character 6et
!$6
!$=