You are on page 1of 26

p

Wherever th',sre Is modularity ''''are is the po,~e:nttal fO'f misunderstandIng; Hiding informatJo'n implies a -IuJed to check aammunicstion.

-- that real-v orld program 1Ii- larger ihan the exampl _- inthis b ok, DIJt Y u m " nO'l realize ju t how m -, 11 larger. Faste r _-PU and larger main memorie -

-a e m e it pe ,m 1 - (, J writ Ipr gf I _. th t W luld have bien impractie al ju',t _

f __ W 'lear ago, _ hie popularity f graphical user intc,rface'" h~ adde - greatly t the ,-_-' rage Ieng h,'- a program. _, 01 full-fer 'lured programs 11 d _ are at 1"1 [00,0,0 Iines ID'o'" - ,-lUi n-liru plf- grams are COmDl', nplac '-, • d it's not unheard ... _ f for ,0 pr ,gram b _ e ] 0 millie n line I, r more,

Although W-. n L desizned for' riting large programs, rru n large prugram~ have in fact been writren m C, If, tricky, __ d it require a great deal of c ore but f. I an -- done, 10 thi 1- apter, [H discus "e_hm,_lIc, dl, _ have proved hel __ ul f r writin _, larg __ program: and' how - hich "features (the B ta'ti c storage class, for example) at' " specialf u _ ful.

" ritina I. _r,_i~ pr,. zram 1 ',. len calle d -.roc ramming-in- I. e-I ·'-~I, '-I!I', ]·1 quite dif-

ferent from writing sm U one -if· like the di nee betwe n _ritin~ ,I nn _ ,I er (10 pag • de uble-: aced, IOf COOT e and ,]1 O=-P~~··' book.v large pr, .~ ram requires more attention to style, In '8 many people will be orkins on ·H,. It T I, uircs "arefu! documentstion. r_ uir . plannin" " r m. inrenance. inl if: it ' . ill Iik 'ly be modified marr time."

Ab "a11, 18 lar ~ rusram requires c ,-. fu] d,·t n nd mu 11 more planning th' 11 a I ,m·w U P'f _ ~ ,m" . ',.. . L KR'_ '£11· _ ~ _ ,i,'-'n . r I "lll, malltalk p 0 rammin . l nguag '", puts iL ~you een -bui~d a dogbou· out of ,lllY:lbin,g.'· A d gbou e can be built- withou ., ,- ... p,I_· icul - I 1,-1 'n l .. in, - h ,.~ ,·~'r .; e -'. _ .. ar - at h:md~'~ house

for humans OD the other hand is [ . omplex [0 just tbro, together.

ICh pt! r I, I dl cur ,", ed writing Iarg , prll- ams in .' but i C ,n·· I ~aled OD Jan-

guage d tails, In thi I, bapter \ e H r~' isit th t pi "~I thi time focusing on t ch ... ni, ues for good program de Ign. A complet diseu si n f pro. - i o'~ iw I" nd the sen ie of . is book H'9l- .' r, I U 'Itfy '"0

484 Chapter 19 Program Design

~ orne irn ~" " rtant c nc pt in rogr ~ d esi and 110 ,hw .u _~ them to creal'

pr l!Jam~, that are read b1 td maintainable.

1'-1 ction 1111 dis ,'"I hoi', I,' iew ',_ pro,_ '~- m '-': , U eetion "f mo ules

that nro id ~ rvie -, ' [, ell, ther .. W ll then se how theconceors of in rm tion hi ~ ingSe ti n 1'9.2) and -II,tr _ t dat ,c CI" f "l:'b,1 '0 - 9,.3) 1_ sn improve nlod,we, ., By til u ,"tl .rm a single example (Q t_ _k dau 1[,-' 'I. :c, ction 1 ,.'1' Uta_ ate how an abstract dar typ can ne c~nl d and implemenn din'. Section 1 IM5des ribes some limitations of C for defining abstract data . pe I and she s hw [10 - 0 around It I' ' JD.

a ules

,0 deslenin a i, pro-a -- (I, r t1 pr, gra in 11, II her lan _ ua, ~ r F th'l t mar n, if'! - often u - , fill to view it ~ " a numbe 0"" in lepend nt lIllodrl,les'"1 A module j a eol-

le nion of [.VII' _, ~ '" m:c of which ar m d, I, I . 'i 11_ I 0, othe - P t, 0

'he-li'e'III. - '~ Each mod ule has 'n i"t_'rlll e that r I ':- - ib _ " the I,l ailabl Til detail Q- 'till ~' rnodu iiel~ ncludin lb, I '(J,UfC code for the stc ed in h" m dule ilJzplrflL'.6',nl! - ~'QI~-.

I _'n I ' f/', ~~'I' ervic es" j- - 'uncti In: 1 The int C,-'I 01 'I ule i ' a

header fil . containing proll-(~ pes _.01" [he fuacnons lh t rill be mad a allable to

cl ients I " u, TIe,'. Th - imph m _nhlli In ' 'rf ltd J ~ is : ~,U[it;' - I '

de finition ofthe m duk ' .. funr til' 11 '~

T 111U'~tr,';t. thi terminol gy\l II-f'- I, ~I", -t th calculator program that was ~,~ I t hed l S ti' n 1- ,..) nd I ,- - I. - _ ~ ~ p- - ID. i .t nf 'the ill ' Cell c .. c.

which c 'nt:~ "11', the main '", 'OJ "in and ala 'k module- ,hich jl I I, ton d in th iles sta;ck",h'Ddstalck.,c(~le he Iigure at th tcp f tbe ne tpagcf. ua.Lc .. c i a cliem of' th ,~ moduh ~ atack~ h . lh ;,11 tJf .' _' the ~II k m ule; il upplie I" er thing tb. eli, nt need' t I ~DJ" - , about' be module, stack. c 11" he

in ,I'J,ll,rnentat,iun of the mod JI ': it I mtains d'!- fmj[i ns of the sn e', fUD ·001 a, ',- I ~ Idee lara" 10m f the v J i_ bles ha rna_ c tip

The library it. , irs J '_ zollection t 1- m dul " Each head r in tb library

er 1_' a lb. interf I'e 1 a modal - ... <: s tdi_o " h», t . unple L the inte ~ ,I - tc B.

m I ule ,n. aining ]10 unctions _ blll < sri n9 ,~, h~ ~, the in erfa ' .. ' I~ module containing stri - ig-handling fun ·'Li ' .i~., Divi ing 'f pro aram illil I module ha



'I e I~

-, them-



moduh .. ' I 11- Pi I ., perly de 1~IL_ed- 'I I "3n tre . r hem l!! a'bstTac~

:.~ il of how

11,,'1'", m· ',re., k on the

"include ,~stdboo "h':>

void. Make_empty('v'oid) i bool is eWIP'ty 'aid) ,i boo,l J1Ls-fu111[void~;

void push (int i)1 ,F

;, nt pop (va.id) ;

int mate, (va±a) r '\

tnt contents [100] ;' int top -= 01;

)

voidmake_empty(v;oid)

{ s e.e }

ea Lc, C

bool is fu.~l' -oid)

( ~ ) -

void push (in' i)

( ~- )-

stack.c

ular pers,on .. Team member, can then work largely tndependently of ne '~ n nth er,

-: ,_,,-tJbility~,~ '_ ,Y' m, ule tb r P ides servi __ . t· p, r _ u abl .'

P'li grams;> Our . tal mo u~ _ I fi· example; i reusable, (, ill .. it's 0 -'" n h " 1'" anticipate the future uses of ,0 module, it Ii. a good ide rtn .. " gn module: 'or (I eu ability.

• I. atntainabili_ ~ . _ mall bu - ill u uall ,.;J( only' "',m_ Ie m dul impl '-

mematioa, m,_il. ' g th bus easier t Ioea I' and fix. 00 ~, the bug ha been . jed, rebuildin the program r uir I '. n1,Y a recompilation 0 ILh: -, r dule lmptememation (follow1ed by limiting the entire program), On a lars r "calc,

·e could repla . - au, enti m 'I. ule inn j mentation. pethap to improve sr forms ce r I . ben _~n ~p rtins ~", -;rl'gr '. ' to a ' .. - erent pl~ torrn,

.. J though an [hi .. ,e ad vanragl - are' impo - an'l In - intaiD' _ iU ty .. lh" _ m.I., lid .. cot Mo ,t real-world pro nms ar - in service to er a period of y- rs, during which bug ~I ar disco ered . nhanceme ts are made, and medific I' ion ar mad = t m _ e[

hanzms reoul · · · ul f hi 1L.-. •

C anging r quir meut '. e: -gUID' ,,_', programm am,' nr ,8., Ion mac mamte-

nance much le~~ i, r; runt inin program . h nild be like main . ining _ car- fixing ,8 flat tire shouldn t r quire o· erhauling the engin -,.

Far anexample .. \VIe need I k no further than the inven't.ory program 'of Chapters lltJ, and 17. 'The original program (Section 16".3) stored part record in an array, Suppose ah,ftL, aiter 11- j ng this progr m for a while the cu tomer objects to having I, fixed limit on the number ~f paru that can be tored, To satis ~ the ens ... romer, W' might switeh to a linked li t (a'~l- e did in' Section 11.5)., Making this change 'n, quired going thre ugh the entire progr~~m~ ~o,kln,g for all place --- tb~;,1 depend on the way parts are ;, toted. If we"d de igned the program differently in the first place-i-with a separate module dealing 'with p,arlt0cage--·we '\vauld have only needled to rewrite the implementation of (halt module" no' the entire program,

Once we're convinced th,a~ modular design Is [he 'way to go" the process of designing a program boil down to deciding what modules it should hav ." what services each module should provide, .. mnd bow the rno· hrles ahould be Interrelated, We"1] n,QW look at these is~,UC,8, briefly, For more infonnt1_lin abou1l design, consult a $0=11 ware engineering [ext, such as FUndfJn1r!fltaJs of SoftwareE n.grn,,(!erh\1 g, Second Edition by Ghezzi, Jazayeri and Ma,ndrio]] (Upper Saddle River N,.J.,: Pren-

.• 'L:1"",111 2·011'13-)

nee- r,w " . .u -'I.

Good module interfaces :IJie"'~t random collections of declaration . deigned program modules hould have two properties: .

• Hi" . clJ,hesio',',I:~, The elements of" each module should be closely related tv on c another: We might think of them IS, cooperating toward a commongoal. l-li,8h cohesion makes, modules easier to use and makes the' entire program easier (0 understand .

• Low ,C'o,gp,li:.g, .. Mednles s,bou1d be as indep nd, nt ot" eachother ,iI" pes sible, Low' coupling makes ireasier to O]odll)! the program l1.11ld IF.eUS'E; module 'II

Does tile calculator program have these properties? The stack module i" clearly cohesive: i·t" funcnons represent operations 011 ,8 ' tack. There's lliUle cou-

-lj'li'!ii -'"- - '~11 - ',- oeram Th ,,-'--"~ 1 ~ . file' de --,' die - -t -' -k- h (-' d ,- -t ' -, k -

P u.g to IU e pr "tiI~ ~ _ e e.a, u. '.' C I, I epen ,S all S, acx, ranc 8" ae", .' C

depends, on s t ,9. ck ., .h, of course), bu_t there are "10 other apparent dependencies,

Types, of'Modules

~£lD.a1: A h> he3.d~9f lP2,3L l' <.1 .i, m1 't a ~ .b ~ - h~~d9F' .'232

Because ,of 'the need for high cohesion and ~ow coupling, modules tend to fall into certain typi(;,a] categories:

I. A dill. ]loo,l is. ,S ccllection of related variables and/or constants. In IC~ a modu le of this ltype is often Just a header file, From I design standpoint, putting variables, in header fi],es i ·n'lt usually a good idea, but collecting related COD~ stants ina header f le can often be useful. In the C library, -c fLoa t .,h> and <:.li nrl t.s ,i h> are both data p _O~:~l.

- A ,li1Jr_arJ is a collection of related function s .. The -e s t: r ing ~ h:> header for example is the interface to a library of I tring ... handling function .. '

• Anabl·"lrrl,·",/jllc L a eollection o unctions bar openae on a hidden data

structure .. (In this chapter [be term I. object" has a different meaning than in the rest i f the ok, In ~ rmmolog ~I an object is simply ~ ~ lock . if me m-

" that ca ~ tor, ~. i]U. '. I.n thi b~ pu r 11' 1\11. r .. r ,an - - i' t i ~. 0"

I • ata bundle . Oil the I· ,. ' the. " ,t:' i' hi klen

abst act, ')

·rory-

• . n rdiSUll'_ data,. . , . type • ho e re pr ~ entad _ n is hidden, eli, nt

modules can u"e th tl/parl, 'e des, ut hav D' - cnowledge _ the

arucmre I. f th e van b • es, 'eli at m . - ule ,.1 perrorm .c _ IP rati n I.' D

such 3 variable it must call ,I functinn provided by the ab t =,'-, ( dat;l t ' _ modul . Abstra :-1 d ta types pi y a significant r Ie in modem rogramrnin ; we" U r tum- them it! . 'eclt n 19,~3--] 9.S.

All- e ign·d m ule ,_., ~ .. ps sc me . orm fa cr 't _Or m iu eli ~nt ... li-

. .n ~ '0' sur s_ ~- .... me ule ,f· '," nple ~ ha, 11 .. need to kn .. . hether th, l i

.. - red in an arroyo in ,I linked li ··,t, OT in some tb t rim. D J I . rate Jy COD, - sling D nforrnation from Lhe clien " 0" a module is known as. i'I'fo - I - nOI "idi" , .. Inferrm ~. i n hidin 0 hs .two ·rimary _ dvautages:

_. '" d. n t kn _ w he W tbe t;_ ,e ~ _ ,i' ~,'011 d, th Y '. ' on" t be ~ cJ _ to

orrupl i" by amperlng rith Jt ~ intern 1 orkings, To perre rm op r tj, n . n the stack thev' U have 'La can luncti n '. that are' provid d by th module It ,eU"-funcli .. D· thar v e' r: written and. t =., red,

• c_ Ie» :bi'lt .. ,.' - ing chi' g ~n rn -l er how la I. --(I ~_ In. dule "L internal orking WOD,"t b iffi,1 ult. For example we ceuld implement tb, tack a

an arrayr fir.,l then later witch to ' linked lis t Of' othr r p._ · c_ntatiOD,~

We"U have t 'rewrite th i-ml['nlcnlati'DIl ·f the moduli ur course, but-iF

he mr idule ' .. de signed properly-e-we n't have " alt r the module -

inte face,

In C, [be rnaj ,r L,oJ, for enfor in informati n hidi - g j' the stati,e 'S,( age Bt.stin5tinlag~das8 ~nJ.2 ela '., Declaring a variable witb file scope to be at.at.Lc giv,., it internal linkage, tbu [preventing it ft· 1]11 being ar I~' ed . 'om orb fr ., Ies, incl -, ing lients nt" the dul .. (Declaring a function t _, e at.at.Lc is · ]'1:" useful tho func ion can b dir tly called nl b ther unctions in th . am - file.

A. 'tack Mo -~ ule

o 'I - the benefit of information hiding J .... . 10k ,at two implement rion

stack m dule, on _ u ina an arr· and the other · I linked lis t . The . .. du ~. _,~" had ~r fil wHI have the following appearance:

488 Ch,apter 19 Pro:graml ,Design

s'fs\ckl,ti -#i,fndle,f STA€K H, :tI;d,efin.e ST~C'K Ii

#inc:lu,de <stdlhool. h>,

;- C!99 only *1

void make ...... empty (v.Qid) i bool, is_e'mllp,ty tvoid~ ; booI is~f·u.l~ (void) ,: void push~int i);

int pap('vaid~ ;

#endif

I've included C99"s, <,6't:dboo,1 ,. h» header '-,0 that the is, empty and is ~fu~1 functions can n~~turn. 1\ boo1 result rather than an int value.

et 's f rst use an ,alTay to i ml plernentth e stac k:

s'l.clt1,c . \ Lne.Lude < BtdiQ .' h> linclude <stdlib~h> iinclud-e iI,stack"hU

#define ST1\C:K SIZE 1010

static int corrt ent.s [STACl{~SIZE]. ; static int top = 0;

,static 'void terminate fc"onst cha.r *mesQagll!)

{

pz Ln 11:;: f I( II is: \ n .~~. mea sag'8) If exit (EXIT=FAILfJR.E) ;

vadjd ma,ke_empl:,y"void)

{

ttJP = 0:

}

boo L

{

}

bool is full (¥Did)

{

V,Q ie. pU-Sll ( in t _i)

{

if (is_full ( ) )

t. e.rmina'te ( II~ Error in pUSll:: stack i ,8 full. II )1 ; .eont.erit.s [top''t''l''] -r i;

}

in't pep (vod d)

{

i.f I( ia~a'mp~y' ( ) )

termin,~te(,~I'Error in pop r st.aok is e:mpty,. il'); r'et.ur'n orrn t ent.s [- - "top] ;'

}

The van b),e8, that make up the stack (cont.ent s and tOPI) are both declared at.at.Lc, since there's no reason ~or 'the rest 'of' the program to access them directly. The ter'mina.te, function is alsodeclared s t.at L c. This function isn't part of the module s interface; instead if, designed for ue solely wlthin '(he implementation of the module,

A a aaner of ' tyle, 'orne programmers use macros to indicate which func .... tions and variables are "public" (accessible elsewhere in 'the program) and 'which are "private" (limited 'to a single file):

#de,fine PUBLIC t= empt.y * I #define PRI'VATH, atat.i,c

The reason for writing PRIVATE in ste ad, of stat.f.c ill that the latter has, more [han, OD_ use in C,:, PRI'VAT'E makes it clear that we're using it to enforce info m,8J~ tion hiding .. Here's what the stack implementation would look like if we were to use P·'UB" 'LIe· an' ... 11 'P,'RI'IV''"fIITE·'

IJl-:~ ._L_" _' I"'~ -...J_ .~:' :u. ~ ;.,-1 '.I.'~l.-· ~

PRIVATE Lnt cont.ent s [STACK SIZE] ; P:RIVATE Lnt; top. •.• ::: O';i

, '

'PUBL,I c boo'l i s ~ empt; y (va id) .( ... " } POBLlt(:! bool i,3 full (void) -{ ., ... ' }

prUBLIC in:t pop (void) {: ... }

s,ta't:1c2~c ~.in,c'lude <s,tdio ,. h> #inelu,de <f~rtdlih,. h:> ~ I inc 1 ude III staok .. b ~m

at.zuct; node ,{ int dat.a r

st,ruct node =next :

} ;

st at.Lc at ruct node *top -NULL;

static valid t,e1rminat.J21(COns,t chaz *·m8.6B.a9'~)1

{

pz Lnt.f (~~ %6.\0'111, me·ssage) i .Qx.i t, 'EXIT F1l.ILtJliE) ,t

}

VQ,idl make'~le'mpty (void)

{

whi Le (l i s_.eRl:pl'ty ( ) ) pOTP' () ;

h'ool

{

}

'bool

{

}

r"e t.u ~ f =;, 111 E!t.D ~

.IL.,. .' ..... ,iI;;L . aA,..."",,~ ;'

voidpuah (:i rrt; i)

{

·s'tru·c·'t, node '*ll,e'w node = malIce i(s:izeof (str.u.ct nod:e)) ; i£ (new node == NULL]

term..in,ate fit Error. in. push . ,s'ta,ck is 'full ~ II) ;'

n.lew' node-o-dat;a. = i~' new node->next ~ top; tojp = ~w BOld1E!;

at.ruct; node *'olld_'I:,o'p.; int i;

if (i,s~empt·y {) )

t.:e:rminate I( II Err.o.r .in POIP:: stac'k is iempty ~ '!'I) ;

ol,d_'top :: 'to,P i

i = to'p- >data; tap .=. tlop'" >n.e.xt. ;' free' (Ol'cl_top) ,: re.t~urn. i;

}

Note tbat the is_fu11 funcrion returns fals~ every time it's called, A linked list has DO 1 imit on its size . 10 ILb ·:tack wil I never be full, It's p~: sible (but Dot Ijk1ely) that the programmight run O~It (If memory, which 'w'jU cause the push function to mll~ bUL then:' I; no ea y WtiJl'y to tes t for til' 1 condition in. advance.

OIUJ' stack example showaclearly the advantage of information hiding: i'l

19.13

do .,nt matter' h. ther we u,:c stack1. e or ,stack2' ~ c to implem _nt the stac

module .. Both . ,'(. j ,n' - match 'til mo, ule' . int erfa .i~, 1 ,'. 'e un ~" itch from on' ,0

the other without h" rving t chan es else her' i " the p_ i ram,

,es

m '. ule th ' an abstr ict 'I' e "I ~. -. I he ,rue. _-_ duk in " f'e' i -u .,

ction, h. __ · " :1 ious dj, advant , -: tb 'I", ~, I n. Wei_: [I hs vie mulllii . in t nees of the 0 ,~ect mer than one stack in thi ca ' , I,. To accompli' 11 '11 .' ~ e' ~ ~ need to go a ste '1 fur er nd cr ate a new t pe.

One - e' ve de fined a ,Stack t"P " many stack ~ - e

"111 meat illu trat '., hoO' '. e co rld 11. ve t 0 tacks in the same

S,tack s

g- ""'i ,~

" 4. i

make lempty(&s1) ; make empty ( &s,2)1 i

~

pus,h I('"S~, 1):.

push ( &09,2, .2) t

it: I( lis~empty(ics1»)

pr,in'tf r H%,d\n~", pop (&B1) ) ;

Wi "ric not really sure , hat 131 and s2 ~'-_ (structures '? pointer, ,?). but it doesn't nU11,'J:. . ll· . 'lien ' I, :81 and s:2 ~ b· tra -ti .'nl ha ' JiC· P md t .,riain' .. peratioi c.IO,~ (make __ ,empt:y, is_empty i,s_full~, push- 'PIOP'~

L t'l .convert our stalcklih header so that itorovi "I a St,ack typ"--" where Stack is, a struc ore" Dingo, UJ require adding . Stack UT Stack *) par-' - tert .'aL h fun tion~ TIl be' d· win nos I _Oi, I~ 1 iliis I( chanze tc S," ac ., h ' in. bold~ ufll:hanged portions ofthe beader - en't shown):

*dle!i,ne STA,ICft S:IZE 100

typed.ef sitruct., {

1D,"t contlents [ISUTACX artiE]: iQ,ttop,:

} S'tack,;

voidmil.l~e_empty (Skack *9) j' boo'l, i,s_empt:y ('c!Q'BB't Stack 11'9) ; bool is_ful-- (,CD; ,B,t, St,a"ck ... s,) ; void push(S't:_',ck ·'B, int. i)' i int pop (Stack .8);

he stack parameters . make empty, pushnd POIP nee _ [0 bep 'int r "l'luCte these unctions m i the sr C ... Tb paramet r t is_emp '~ ',B'n · s f'uLL doesn ' need [0 b a pointer but I v' c_' In, ' de it on, - an)"" ay~, II' '. ing the ~ unctions Sta,lck P'I in te I in tad ef a st ack value i m re effi ient~"inc'. ~ the latter -~, uld

~l ult i a tru tore being ", - j d,

492 Ch,aptet 19 Pr:agram Design

En, --apsols'ti,on

Unfortunately, S,tack isn' nn abstra ·t dan Itype,!, since at.ack '" h rev DIs what tbe,S,tack, t p reall: is, N, Ithino pr,e, I nt 'eli /Dt~ from usin Stack variable a at structur :

Stack 91;

,sl. tocp = 0;'

sl. oont.enns [tOPI++] ~ I"

Providing ace ~~, to the t.cp land con.t.errt.a m,~mbef allov .client to corrupt ch '

~"""'II,""- .,r ~tilL -- ,J l be lble (1_ change the , ' C ' " are stored ,. ith ut

having to ,se,,;, th ' effect I - rhe chan 'on eli Ill' .

- bat ~ need i \. -I pri en I Iients ' _~ "n1, "n in bw the Stack -~ i - repr sent d." has 0 Y Iimit sd .c upport f r IIl,R,_f Q' -I -,Illan :g type in t '·1 wa '. Ne ver '-bald k n c Itag 'in_-ladiIlS, '++,c Java and C#'J all bener e uipp d f r thi P' 'po

I clol,m II, 't l , 'pre ~

The nnly" ,i that C ~i_ s us tor 1_'.01 psul 'lion l tile "'IOlm" 'ete ,p',e~ (Incomplet type, were mentloru d bri fly in Section ] 7.9 ~O-I in th: QI, - ~" tion _ the len hapt r 17.) Th, C _: t ndard de cribe j ncom ple e ,. -~ e ~ , ' that d [rib - bj .s bu lac '_ info ' ne d.'d LI d terrnine til ir ~"Iiz, ample, til, declaration

at ruct; t;

/* incomp eta decla.ratian Q '~* I

ells the c mnlier tn-[ I ~ " I U"U, ture ta bu d sesn t deserib the memb r of' 'tbl

nruetur '. ~'_ ' a r sul eompit r d esn't h- - I 'ouch Information t ',' determine

the size of, 0,1 11 a tru 'lID~" The inti nt i that n inc omplete l pe will be completed _l! € ,~, here ill th pn gram.

_ "1 lonz sa type remains incomplete, its uses are limite d. Since the compiler

"'Iifi' o. r t know th size of an inc mplete type, it ~, nit,' us . to declare a" ariahle:

struct t 8',i

f*** WRONG ***1

Ho . e c_'r ir " per e ,t~, legal to d fine a point r r P ,.' that f t,', pe,:

This : pe tle initi ' ' I,' tate that a, \'~ riabl - f t- p ~ T i, '. I r poi H'C'f to a I, truetur ' with tag t. We~aJl now declare variables to ' pe T'~ pass them as argurnenu to func-

tioni land ,ertio n otb --r' op er til n ilia are legal f r P in . ; ,.. Ttl ' f

- oinn r doesn't dp nd n what il poims LIl hich I plain' why - allow hi'>, beha lor, bat - . an '. [ de 'I lh su '_ ~ i ~ apply th -:>' p , ator to '0-0. ~'" .f lb, - _ ~',arj,able', . nee rhe compik 'f ~ -- iws n tllin. " "bout the mem er "If ,8 t ,c, ucture,

,~.'N#"ii,h'lI D '"I'" ,A-I jIIllLarll.ll'A#t I' .1" I

(Ve:rS'Dd 1,J

, , illustrare h absn act dat _ l-,p c' be 1_11l . 'P" Iated u in in, romple leyp·'

we" JI develop a : .ac ~ ADI' based 0.111 the ta· 'k modul escribed in I ection 19.2. In

th. p . ess we n I ." plore thrice dirt" rent .. :' y rc im - lernenr the stn

Fir I we 'Il need I bead r 111 .that efine: our stael ·DT't- pe and ,'._~I . e prototyp '- S for the functiom that reprei nt stack p _rlal'ion~,. Let's name thi file sta'ck-·

.AD'T"h~ TIl. Stack type ill ~ pointer [ s' ac,k_::typ,e struc ure that : tore

the actual contents of th sta -k. his strur lure i ' an incompk ·'te It p -- Lh. t will be I ompl ted in the Illc thai impl men . th stack. The rnemb T his tructure will dend on how 'h. sta k t implemented, Her ' .. 11, 't he at,ackAOT,.hfile win 1u, k like:

#ifndef STACKADT' H '" de·fin.e S~ACKADT H

I' leg! only * I

t d f t t t k t ''liSt - .- k

: ype e ,S, -ruC'~ S .acr ~:- ype .' ac I.

Stack create (void) ; void destroy(Stack al;

vo id make_empty ( St aok S,); boo l is enlp'ty (Stack 6)1;' booI, is_full (Stack s) i voi.d push (S.t,dlck s , int i) ; int pop (Stack 5) i

#:endif

eli llt< tb~ ,t in lud ~ a tackAD'T .. h . HI re able [I . d:..' 1, - 1I j. 'bl,~s of typ. st.ack each of which is capable I f pointin c to ' s,t,ac]{_ tJIPlettucto:re;; ~ Iient can rbe n call tho funcri n. d cl- '-;C' in stackADT II h l r, P .. rm . aer till I. tl

tack variable .Tlo e er clk I1t . an t ace ',1' th m - fl,' ers the atalck~t'l'P'e

structure, since tt at s trucmre will be defined in al separate file,

ot ' th t ach function has a Sta,ck p~ m LI"_f or returns n Stack alue, The stack func i ms in Section 9M' h~ d P r ~ .. ter . of type Stack *,~ TI e reason for the' difference 'i tha a St,aLck variable is now a point r;, it pint t·· I· :stack_type structure that to I_I th, c nr n '.' .'1., tbe 1 t ck, _ un .tion needt mo· ify the s ack it changes the structure it ell, 11 t tile-oint r to' the nru - ture.

494 Chap'ter 1'9 PTiogram Design

:, enerall: do sn t need th,_ .~-, fun- tions.f ut " n , d. e crea.t·e ·~iU dynarnicnlly allocau metnory~"r ,a 'lac . including the memory required for a st,ack_typ,etroctur}, as well r ," initializing the stack to u "empty I' stat '. destroy wiH release the - _DC',- .. - r dyn"n ically allnca ed m~mo _JO

Thi _uU,w;ng client' e ean b' U-' ",- l- .l the .·t ~~k AD/T. It ere ites " . (11

",, __ JIIj:s.L,JI'. 'j, nd peru rm' I , • e y IIIP ~.r_ '~'·n . . n them,

sraallc:lien tar C' # inelude <: s t d,io ., h» #include ustackADT .. h"

int rnaa.n (void'

(

S"tack 91 t' S2; int 'n;

81 - cr eat.e I() ; s2 -- 'C,reate () ;

pushl~.slt1 1); pus h ( s 1 ~ 2);.

n ;; pop r( B~) Ii

p1rintf I( npoppe,d %d from 81 \n"I~, n l : push I( 82, n):

n ': PlOP (a 1) ;.

prlntf (!IIP'opped t·d fr,om 51 \n!I.11 n) i push I( sl.2 " n) ,;.

while (1 is_empt,y (,82) ),

printf'("Popped % fr.om 8,2\011, p,op(s2));

push, ( 82, J,) i n1ake_emp: y ( s2) ,; if (i.:s_s'mp,ty'(s2)')'

prin,tf r( U s2 i,e e,mpty\n,ll) i

else

printf ( III s2 is not Is,mpty\n~');'

pr . gram b uld nrc du .. ',:. the

return Q;

}

,~

1 D -=- outpu t

Popped 2 from sl Popped 1 f zorn s 1 P'opped '1 fro'm s2 Po;pped 2 from s',2 s2 is rem,pty

19~4: A Stack Abs,tract Data Ty;pe 495

implement Im-

plest, . te U 11 e lh s,t,ackAOT. c ,- t define I_" stack ' ype _ tru ture ~ '. that

it contain c a fixed ... len tb 3y (to' ho,ld the eont nt of 'til stack) L ng with an

Jut' ,·r that . e~lp.. track of the op '. f the st" ck;

sczuot; st,ac'k_type {

int cont.ent.s [aTACK SI:ZE] I int t1oiPi'

} ;

stackAO'J:c # incl ude <,stdio,~ h>, #includ,e c,stdlih ... ,h> #--incl ude 11' IS tac'kADT ,. h II

# !efine S, 1lCK SIZE, 100

struc-t ,S' ,ack~, ype (

in - contents [STACK_afIZE] ; int tOIPi'

} "

static v,oid termina .. t'e! (conat; chaz *message,)'

{

prin ',( II 'Its \n III, ms'ss,ag,e); exit (EXIT_FAILrURE] ;

}

St,ack create'(v,oid)

-{

S' ack a malioe ('sizeo - (s,truct stack~type}I)~'

if (s ~H~ NOLL)

terorinat,e (,lrE,r:ror an create: st,ack could not. b@ ,C!reated_ I 1 ; ,8 >to,:p =. 0;

re'turn 81;'

}

void deatro¥(Stack s.)

{

free (s,) ;

}

void make_,e'mpt'y (Sta'ck s)

{

b,olo,l is_empty' (S:ta,ck :9)

{

r'Ed:;u,rn s -c-t op =~ 0;

}

stackAD1:h t{ve,rsl'o,o' 2}

beol is full (Stack B)

{

ret.urn ~,-">top ~~ LBT1U~K SIZE:

~

void push f S,tack stint i)

{

if ( is _f ull (s) )1

·termina.l e ('!ErrC!I,r in push: stack is f'011. II) i ,8- >Icontents [s ->top -+] ;;; i:

int p,o- (,Stack B l

{

i _ I( i E --. emp ty ( s 1 >

f lermina'tel(,mBrror in pop: stack is empty" III~I; return ,B->content,s[.".;ooos->_op];

}

The mo: 'I ' triking thing about th ' functions in this _ ~ lie i'" b,a:, the use h·· - .0..;:> o ier,EUOf\ no the ,. op rator to 18~' .ess ttl' cont.ent.a ' . -d tOPI memb f, 0 I tb s,t,_ack_c'yp,e structure, Th S naram -~~r j pointer to a stack_typ,e stru 'ture, not II - tructure itself '0 using I he ~, operator would hie' illegal,

" ,0\ tIl- 'I we have Q working vel '.' ion of he . rae . ADIT- let S try tJe irnpro e it t First. n te that l ·m.'_· in the stack mus t be integer: ,. That' '"_00· re rrictive: in [~_.I, , he item

, r Ie doe n t real]: matter, Th- st ~_ item 1'0 Id jm t ~ I· asil b - lb,,, r •. 1_1: Lyp~

(f Loat; doub.l.e Lonq etc, I or e·" n structur . , anioln, "1 or poin "T' for that matter,

To make the stack AD'T' easier tomm ify tor differen item type ~ilef . add

r pe definition to the s,tackADrT ~:h beadier. It will define a type named IteUl~ r· pr ": .... mting the l) pe 0 data t be lor d . -D the' .sl . ·k,.

#if,nd,ef ST1\,C'KADT !-1 define ST'ACK:ADT' :8:

Stack create (voieD ;

void destroy(Stack 51; votd make~,empty (Stack s) ,i haol iB~emp't¥j(,Stack s); hool is full(Stack s);

void push (S't,cu:k a , ItleDl ;} "' Item pop ("SLiack s);

The change. to the ile e hwn in bold" BII '. ,id}c', the ad ition I . the Item type, the push and pop fun-tins hav ' been mo if d, piaah n .'. has Iii pat met -_ of

t.YP I t ern, and P'OP renu 0 --, Iue eft It em.- ". 11 U'L! __ • -, e ion

st,a:ckAD'T ., h ~~, rn n I. n: It replace ill.'. ,rii_ r ~r, ion.

The st,BckADT',,, c fil •. ill n_, d _ I be modi __ ~I. l match 'the new s't,ackADT, h, The change an minimal, however. -t he stacJc ~type~trllc .ure will ]lOW contain an array wh se element have t ,1'_ Item instead If Lnt.:

atruct st,aJ:::k_type {

I't,em cont.ent.a [STACK~SIZE] ;' Lnt; top';

} ;'

The only other change: arc to plush (til ,0 e ond p( __ ameter now has tyPI . !._ em and pop (which e tum', 18 value I r lyp _ I tem). The b dies If push and pc,p - ~e un hanged.

Th stack,alient .. c file an be ',-~ d to te ·'t the n. ,,- stackJU]T;o h . nd s.tackAO'T" C [I ... rify lhattb" Sta,c·k p '. ~. till works I it d: ,1)'. -, . , we I-an change th item typ1e ,U1IY lim . we want by imply modifying the defini ion I f the Item Itype in s,'tackADT" h,. I Although "A' won t have to chan e the sta,ck~ AnT .. c file, w;-' II . Iti It "' _ d .0 recompile 'it}

1m '1 "i!! tb ·'ta· k AD'T' U II D •

p[ __ rnentms .' .' '. "1 e' ._' I'" ,--In'; 18 , ' -. BlI! .

Anoth r probl - ml with the ~. ,8[_ k AnT . ~ il.~urlientl ',t"od' i." tha - -, ch . t ck bp I, :,

ti eed maximum i .1-, ,hi ~'b I UT'l1 nU ser at 11- items, This limit ,. n

;'n'l ~. .-1. d tn an num _ ~iJ 'h~ I, f cour c, - ut ~ n·t· , " ,rle~c' e using (he Stack ype wH1 ha' the' arne limit Til '. n ,way t . b ,':'tta,' ~ 'w-illl different capacities or to .. tll 1.'-,- iz as th P gram i~ running,

Ther are twc solu .ions [0 this problem, One i s 0 implement th e staek I'~",- II Iinked list in wl1ieh "'1. tiler s nr fixed limit nnits . iz Ii' W'j];n esti _ ate lhjl ,oluti n 'in a moment, First, though, I'~, ,'. (1'U1 r i~ ppr -. .h . hich in ' I '

d~namICBJ.I!I' lIaeated ,arm:,! ~ '7.3 to rin st ck it, in t " [I' mi _ally aU[ ., t' d __ r _y",

Th cnn to th· latter appr all i t m ill the srtack_typ,e ucture si that Lb contient.a memb r j ,~. ,01 f 'r L .th arra in . hich lh. items " 'e stored. not th . array itself

struct a,ta. k~type t ttem 'iICQ'll't'sntsl; int top;

int size~'

)- ;

I've so addeda new member, ,size.lthaL,li'.re· the tack" rm simurn ize (the h~ng'th,of'mearr'ly'[h'·.lclcn'tentsp·iD: '0), ···,enu.·~ this rnemb r n che t for the k,ttack full condition.

, he' cr'e'i3' e funcrton will DOW have a parameter that .. ' - e .ifi -"' I the . esired

stack create(ln~ size) I

When crea t@ i called, it win cr __ re s Lack _·typetfu tur (}II,u III arra 0 ~. ngth 5,1 ae .. The oont; ents member of the . tru 'uri.' will p iint to this array,

The s'tac.kADT ,. h IDle '\\/j]II b the s nne as, befor " . xc 'p1 [bat w' e'Il need to add a size parameter to th ere.,ate function. (Let's name the new ersion stackADT2 iI hi') The's t.a'okADT . c fil _ .. in need more extensiv . modification, how,e' er, Tb -, new version a pear b 1· w~ with change, . bOWD in

,s,tlJ',cIcADT2:.,t: #incl.ude <:5Itdia h> -#include <stdlib ~ h» jinc'lude 1-s'ta.ckADT2 ~hH

,e,! 1""UCt ,stack_'type { Item ·CCD't,s,nt;"s i int to'p;

l.D,t S'ize1i'

} ,

staotic. void tlerIDJ.nate, (C,ollst C!b.ar ~me9,sIJag,e)

{

print! I( u %,9.\n 1'1 ~I m,ess"ag'e)1 ~ exit (EXIT_FAILURJE') ;

Stack create (int size)

{

Stack B = mallo'c '(siZe,Q'I (8 ruct: s'taq;k_'type)I)1 i '! f (- "'1Tn TL·· "u

1.. . ,S ='- .1-" Y ~ J

t.ezmi nat;e (~"Error in create: stack cou'l.d riot; be create'." I) 1 ;B,~>,eontBnts, ,= ,ma:L~'Qc [,size * size,Qf {Item,') ) :

if 1(,s-~lIc.on·tent:B =~; NULL) {

fr'ee (s) ;'

t,ermin,a'te 1(' ",Eixror in Iczoe"a"te I s1t;,ck cou.1,d not b,e cr,e,a.t,s,d .. , H', i

}

• •

s ~ ::>B1ze -= ,S1ZS!,;

re'j!o.., rr'n 6' • . IL;,.,~ ... ,

}

vod d destroy ('St'Qck, lEI)

{

free(s-~conteDts) , free (.91) It

boo l

{"

}

ia~[empty (Stack 9)

bool is full(Stack s)

-

{

~,=. - "'. u- rn· n ~ - .... ·til'"'ll'n _ _ s- ,_, ..... s-.r;; 1IJi2 e ..

:.L ~ II;... ~,.,- _ """"~' - _, -,-,-. ,I!l' _'_'.£,g_ 11'

}

vot,d push I( st~ack s Itlem i)

{

if (ie~ful.l (,s) )

term_inat,e i( UE:r"l"',or in p1us,h: stack .is full" I'll) ; S ->C~lclnt,E!n't,s Ls ~ >t,op'_++ ] == i;

]

Item pop (Btack s)

{,

i_ (i,B_empty (s,) ),

terminate (~rrEr:t:lor in pop, ; ~rtack is empty'~, I~) ; rleturn e ->C.OI.aJ:ents [ _ -'s- '>top] :

}

The Icreat,e function :D'DW calls malLoe twice: once to allocate at stack, t.vne

~ J~

structure and once to allocate the [array that will contain the stack i ern ... -. _ ither call

of ma t t.oc [could fall causing t.ermina'te to be called, TIlle ,destro,y function must call f'r'~e twice to release an the memory allocated by cz'ea t e.

The stac,tel Lent; 'I' c file can again b 'used to test the stack AD'T. The calls of cr'eat,e will need to be changed, 11ow1ever"s,1nce cre[at@ now requires IJ1 argument, For example, Wit could repl,alce dl'e statements

9:1 ~ c:reat,le I~) ; 8.2 :' C rea;t,e C) ;

sl - create(lOO); 92 = craa'tl@; (_2DD)1 :

Implementing the Slack ADT Using a Linked List

Irnplernentirtg the s~BCIt A_DT URiHg ;1- dynamically allocated arraygive I us more flexibility than using a fixed-size array, However, the client 1.S still required to spec .... izy ,I maximum size for a stac '. [Bel the time it's cleated" If we USIC H, linked-list implementation instead, there 'won't be any preset limit on I besize of a stack,

50'0. Chapter 19 Program DlsfJign'

'Our impl men a ion will b. irnih r to 'th. in th· stack2 .. e file of '. ec-

tian ~0I.2. The linked li ",I will c' 'o,j t of nodes, .~. pre. eo, e by the following stru 01],_ ture:

at.ruct; node ,{ Item oat.a;

Sltru,C·t: riode *next; } ;

The typ" of th 1 dat.a mernbr r "I-~ _'W Item ratll' r han i i It .. b [ he stru nure ~ otherwis . the same as before.

Tb ,s I' ack _type .• I ~UC' ILl! .

Is't'ru,c't: staclt~typle ~ struc't node . tOiPI,i

) ;

. de i _ . ·16. .... ··11 ',.

n . e In Ui;: '"

_'l first glanc [he stack_'t.~ uructur eems superflu u ~ .. e could jut

define Sta,ck o be struct no,de 'Ii and let a Stack alue b poin er o the

first nod In the list, H', ,e, er, ~c . till need the st ack_t"ype tructure s 0 'that the lnte c'e l- .. he ~- L_ c_ rlem, ins unchans ed, (If " r jd I" ,; y ,. i1h i "' ~'y fun '-, ...

Lion tb~'t. modified the ~·.,'a,c'k 'would need __ S aok parameter instead of a S'tack parameter ) sorecver ha in- th st,au~:k~type tructur ill make it

I c ie:r to chan I the impk rn mation in 111' uurre, should w decide [0 store additional i nfonnation, For' I· mpl i ~ I ' t t r ci It that Ull stack ~ type ,truetur should ' : .n'[t. in a count " h w m . v it '- ire ICUI'l, ntl uored in the "lac - we can I sily add a member to the s;tack _type- tructure to ',lr'Drl Illii~ in form _ -

,pr:in~ f ( I~ ts \n.1I ,t mess,age); ,ex:i (EXIT_FAI'LURE);



1 [1,.-

We WD,J]"'L meed UJI mak any ehanges to the stack1illT,.,h bead, .. IW_ ]I u:,- this b ad r file, no' s"tackADT2~, h.) " _ e coon ' - .,101 U'I the " riginal at.ackcLi ant; . c 'ilt, 101' tine, All the I. ban' Ie will be in h s:tackADT,~ o ile, I ere' '- it .. ' new ersion:

sta,e-,' 'DT3.lc '"include' <sltdio. b" "~include <stdlib .h~

o 'IDel ude t' s ackADT ~ h il

,struct node ( Il:lsm da a,

st-ru~:::rt node *nex't i

i ;'

sta"ticvoid terminate (ccnst; ch,ar *mf!ssage)

{

IS'tack e'~ea'te (vc&d)

{

Sta1ck s :: tnaI Loo (~izeo'f (struct SJtack~typ,e)) i if (5,.== NULL)

-termin2tte ,( ~1'Error in e're'atei: ,stack oou.Ld not bile created,. Ill) ; ,S - :>tOlP = ~L.;

return S'li

vod d Idestr.ory' (Stack al

{

mak,e~e'mpty(·s)' i . ree (5)1 ;

}

vof.d m,ak1e_lempty(St,ack s )

-{

while (!is_emp-YI(a))!

POIPI (s) t

boo'l i5 __ empty (Stack s)

{

return B,~·:>'top ;:= NULL;

}

bocl is full (Stack s)

{

return false;

1

void pusb{St,aclt S't Ita,m i)

{

stru,ct node ·*new node ;:: malloe (size',of (struct no,de))I; i£ (new node == NULL)

termin,at'B' 111~IError in puah . st~ack is fu11". ~il) ;

new node-o-da t a = i;'

- .

n~'w_node.->n,ext ~ s,->top;

S->t:·0p = new node;

}

r- em pop (Stack IS 1

{

struct nod@ *old_top; Item· ~;

if (ie_ empty (s) )

terminate! ('~Error in pop: stack is empty. I!II) ;

old_'.op ....; s,->·toPi i = 'old_top·- >d,ata;

s .... _>; lOP == old _ tOIP ~ >ne . t ; fr,@e I(old:__·top) ,;

"I"eturn i;

}

502~ Chapter,'9 Program Desig:n

Note that ·~e Idestroy function calls m,ake~empty (to release the memory occupied by thenode , in the linked H, ,It) before it calls free (10' release the; memory for the stack_,typ,e structure),

Section 19,.4 dese rib ed a staek A " and showed several ways to' implement it Unfonuuately rtlli, I ADT sut er from several problem tha prevent il fro IHI being indu trial-strength, Let's lock al each uf these problern~ and djscll. , possible solution'~ .

The stack ADT functions currently h - ve short, easy ... to-under tand n,aU~:ME~S,: ereat.e. das t.roy, m,ak'e~e:mpty~ is, __ ernpcy, is_full~ push" and pop, If w have more than Ollie .A'D'T in a program, name clashes are likely with functions in two modules having [be' lam' nam ., (Each ADT wul Deed its owu cr'ea,te' function, for example . .) Therefore; we'Il probably need 'to use function name (111Ql inclrp ':rat,e the name of the AD' ' i ,elf,ucll as, at.ack create in' tead of" ,cr1eate.

The srack AnT deals 'with error: by displaying an error mes I age and terminating the program, That's 00' a bad thing to de, TIl programmer call !avoid popping an Icmplty '. tack or pu ihing data OI.n-tOI Iii full stack by being careful to call i,s_'empty priorto each call of P'OP and iSI~full prior -JO each cal! 0" push.: 0 in theory there's ,DO reason for a call of 'prush or- pop 'to fail, 1(1,1]1 the linked- list implementatien, :~10\VleVer'P calling is_full i n't foolproof a rubsequent call of pu;sh t;, n still ihl1l.) Nevertheless, we might wanrt to pro ide aw,ay for at program '[01 recover from these errors rather than terminanug .

. An alternative is to have the 'push and POPI function return a boo.l value 'D indicate whether Of' not they. ucceeded, pnsh currently ,II a , ,8 vod.d return 'Lype~, '

it would b _' easy to modify it to return t rue if the push operation succeed: and false if the stack Is full. Modlfying the pop function would be more dj_fflcuI[~ since pop currently returns the' valuethat "N'S'· popped. - Iowever, if pop were to return a pointer to, 'tbi value, instead .. ,f the 'value itself, 'then POPI 'COU ~,d return NUL,L to indicate that 'IJ11! tack Is empty.

A final comment about error handling: Tbe C standard library contains :' as·aert mBrQreI )j!.·24_1 parameterized maero named aaae rt; ths tcan terminate a program! if a specified condition isn t satisfied. We could use calls of thi 'macro as repl. cements fur' he if statements and calls 'of termi.na'te that currently appear in the stack .ADIT.

~ ta,ck~ I)~ , __ d .. I

, nri . 0 he stack AD'T"~, Stac'k t '(_' .~ _.

C U)I' I

tbe st.ack~ r ,r

void Illsh(Stack s~ voi~ *pl; 'v'c"id ""pap ( S,·t-,ack s l r

PIOIP' r tu -- , point r t the item p .'p returns a mll . oimer,

Th· I 'if I tw' I i a ' ,n. es t u in~ void "lit ~ I L _ L . 1 c • '. 01," i' ha his

approf.j cb does 0 't w'. rk for data th at can t b =.' represi . led in poi nt. r £ rm. Items

c uld I', trms I, which . r. 1"', " .' en .... I Y a inl r I ' . ~r _ h _ _:, _~. ter ill lb-

strin or d nami 111', a~l~ eared L [_ U tu "Ifr. bUll n t b __ 'j',. _ ch .' int and

douhle. T111- other i '.~ d anra _ i'. that rr r ' I . sibl .

t cs .. tha stores void It i ms ill happil alii" t p Ij ~', the e': no W' , It - I 1I trct n 1= nil r ., us - dr .ID .I

Ip "

.. tal:_~ -. if th

. .

,1 empt I

AD

,

that w - '.'

dare d all \ ith mu b m ·rl

. - efi nin . eOI lli , -, lng the it m yp

++- f r Ie " rnpl

I I'll

'. 'JIIl

., .

Q:

• Ii!

'FILE_, pe d tn .in ust d ·lar, __

, lLE: typel ,.22. ,I < S I ,di a ~ h> I ~ B -'- f Ir '.' - rt rming ',I - abl ,ftyp FILIE *:

FILE *fp;

Th fp arial JI will then be . (0 ' ari 1.)1; file-handli ig men ns,

.nr I xp cte rea FI" 1 E -. Ian '_ I,. uacti I "T n

to knw what a FTLE 1, in order to u . tb FILE pe, '.' esurnabf FILE i

tru tu e " pe, '. ut thet _ tandar ", ~I." .... n tel D guarantee th at In -a _- it ._.,iI.._- tc much, I ,lout h -"-- FILE . U 1 i ire stored. 'm ~ ~ the definiti

FILE Ip, can land often do ': I V,r: -, comeilei

:U~:"I w· .can alv ays [oak in hie at.dd.o .. h file . FILE I,~

Ha in de n ,,0 I ther 1 ree -nl u. . fr 'In .' .," 11:- 0 - I:. t· ' I.' ,- .'" th . in' -_' ~

nals of a F'ILE .. Fa m I, .. rnigl t dis ~o, I r tb'_ FI"I ,E ]. " . trUl, tur with a

m ,- be r owned bs i z e 1I-' file -, buffer ~.jz'· ):

-Y'Pedef ,struc {

I buf_er size 'I

(j I

} FILE;'

ID_ . cnow about the bsi,ze m iber rh re's nothing 0 arevenr u from

,_., ,'in, the buff r ize ". - ,I' unicula 'ile:

o in' . n i· __ It ,j nood l,' " hi' " "r _ '_.U " 1-.[" .1 moilers -

-~'

buffer size unde a d~ f r nt name or keep, ", ck ,II il in some ntirel

w ,",1_ '·0, h e lh, " Irs Lze rneml -'f j": 11. '0 W r

f~p-,bsize =, 102 f

n111'" . I_n,w illthe detalls

to do, - en L WI 'l e next rel_ 'aile of th .

,~'r ". is a, dangerous thing

~,I-;"""_ " . h I. Ij I~r t ' mpiler r

IQ':' Wha:t o,tbe:r Ineemplcte l~ ~pes are there ,esl~,e: ineo - , p,l,et 's:trc'tDre 'I ~'pes,? [p, 492]

A:' One of the most CO~mJl10n incomplete types occurs when an array i_s declared with DO specified ,.Ill -'::

ext.ezn tnt at, l l ;'

After 'toi", declaration (which 'we first eneount red in S. iction 1,5.__,) a has :an incomplete type~ because the compiler doesn't knov ,a" length, Presumably ,at, is defined [11 another file within the program; that definition will supply me missing length, : nether incomplete type occurs in declaratiom that specify IlO length for a n array bu.' ~ provide an, i nlt iallzer:

Lnt; a [] = {. 1 ~ 2, ~ 3, } ;

In this example, the arr,~t ,a in!r.ialJ,:Y aa an incomplete type but the 'typ~ iscompleted by 'the initializer.

Declaring ,3 union tag without specifying themembers of [he UmOD also ereeM. ate an incomplete type. Flexible array member (8 c'g'g feature) have an incom~~exlblre 31'1raY memJbers, ,p 1i:9 plete type, Finally, voi.d is, WI inccmplete type. The void type bas, [be unusual property that it can ne cr be completed, thus making it impos .ible to dec we a variable of OU·, type,

Q: What D'tber' I',es,biclio: - is -,8r - Ille I. OlD tb1e Us ,of lneom p,lel- _.' p, ~. '1 ~P'. 41912]

A:, be sizeof open lor can't be applied '[0 an incomplete type (not urprisingly .. ,

.ince rbe "'i "e of an incomplete ryp'e is unknown I. A mernh - r of a structure 'Or union (other 'than :31 flexible IDT,a'y memberjcan't have an incomplete type" SimiIarly the elements of an array ,c,an 't have an, incorru lie e type., Finally, a parameter in u function definition can't have an incomplete type (although thi ' is allow ~ I in ,3 func ion declaration). The compiler ( adjUlst.:~: ,~, each array param rer in a function definition so that it bas, a pointer type thu preventing it f om having _n lnco 11- plete type,

l. fIllIJII;B is similar Ito a staek, IBXC)ept that items are added at ElIU: end but removed from the

other in at - :IFO' [first-In, fu~ . .t~Qut) fashion. Operations on a queue might include:

Insetting ,all item 91 tbe lend 0' the queue

Removing an uem from the beginning of the quetlle

Returning the t1 r~ll itemin the queue (witboun changing [be Ig neue) Returning the la ~ item in tl']Jc queue (w,itJtou'[ changing the queue] Testing whether the queue is empty

Wrille am interface for a queue module in lh ' form of ,I, header file named 'qUI9'UI!' • h.

I, (a rit -, an army based implementation of the q,UCllC module d - ribed in ~x-,rci.e 1. U se thre integers tDI keep b';ru -' 0 th 'Iljueue' -, ·hltU,,' ith one inte r [, ,rrO' ~h_e position 0 the first emptj ,1 1 in th array u .ed 'V hen an ltem i iusertedj, lh _ se ,. lid ,[,'lriIlgh, pe itil," n of the' next item to be removed ... and the third storin the number of" · "em, , in the queu, . An ins -rti n Oil' removal that w rld caus euh rof U,.:: nn l ~W' inte , ~" l~ b iner ment I,

lh IfiLl I, f the nrray shoul lnst ad _~ -,t the vnriable [i. I zer (I thus '_ - sing i' 1'.1 II rap arou nd" '1'0 the beginning I f the I';trf"ily.

b"· rite a: linked-list imp) mentation ,f the qoou, rm ,d.ul, d scribed in Exercise l. two poin ters, 011:1 pointing ~o the fu~ ,l nod _ ia the list and the other pointing '0 th ~ lasm n de, Wh~n an it m ~- in erred irm the qu u add i' the _Dd f 1111' li'L' h." an item ., renu 'vied I om the queue. delete mit fl noue in the list,

(,I) ri I, "n imple ,en. ti 11 1.·1 le' 'sta.:ck t, p ~ assurnin (hal S,ta.ck " c. ' , uu tUI

Udnhtw, a Ji - ed-I .. 11 gth array"

(b Redo the St,a.ck typ li irne 'U ,infl 8 linked [j~ l re pr "ent" ion instead fan

(Sh \V oih stack. h anti stack. IC.)

5. dif. tb ~, queue . h beader 101' -erci - 1.0 lh_ l iL define I a Queue type, here Queue

is ',LJiU,"tUl· xmtaining a fixed-l JJ1" uh . rray . see Exer ise 3(_,)). .,dif, the functlon in

queue '. h ro rake a 'Qu,eue~ param ter,

Sec -;ion 1'9.,4

(a) ··dld a pelek . unction to a tac::kADT ~ c. 'TJm stack .. Wh n called, h returns the top it, m nn Lh

(b) Repeat pia (a) ~ mndif itl@; S II ackADIT2 . e l1li time,

c I Rep"8t pact (a) modifying ,st~-arikADT3 . e ' .. , tim c.

uncti n w i ~ I ha· e a parame ter of ty p. t3.c-. bu t dee ,~l WI dily the tack,

1. -,,- u-'ify stackAJ]T~ . ,e ., th 1 ' , ,k ,lru~ 'm;ui~ally double. ill, size when it b -, ' -'m ., full , Have the push fu etion d.ynamicall,' aUe· ate a new arr y thru'·· twic a ... Ierge as 1.11· old one and th n cpy the ac content from [11_- old arra to the nn. Brie '0.1 1·1 b· e push deallocate the uld ,arnay once 'be data has been copied,

I. ,_: odify P_ : l' mrnin Pr ~' [L from Chaet r JOI, lfll i us-, the -tack AnT d j rib -d In

Se lin 1.11.:'t YOu 'rna, III e any of the irnph rnentations of .' D1 described in 1001 section.

_ di ,- Programming Pr ,~ecl ; urn Ch 'Pl· r 10, lh~ t it u e th Se ti, 'in J .. --, You may U I ,aDY of the implem emations ..• 'th ' ..

II lH Y IhcrtackAD'T3 ~ Ie flle of .... €tin 1"., b, d in,~ n in_ In m- er n m .-1 lien t I

th - stack_ -y:pnl,! tructu r e~ This memb r wiJ] ke "p UtI k OJ. bow many items are I. urrently stored in a tack. ,~dd:.1 n w fttocftion named length that ha;., ~_ S'tack parameter and returns tim alu of the lien m,eID,I-' r .. ',I, 11,e ; f th ~ 'i tin fun Ii D ' in stackADT] ~,Ie will need to _ 'Ie modified a~ I well.j M,od~", s'tackcl ient . e lb.D:t it calls the lenlgt'h

un . in (an dl pla- the value that it _' Ulm' I)' all, . ac'h operation that m dlfie ,,' tack.



Modify lh"~ st,ackADT. h .od ,sta,CkADT]" c files of - eti 11 I~t I 0 that a tack stores values ~ ~ P void it,,:a described in eeuon 19' .. ""', Lhe I '_ ,em ... pe ~, ill n 'I ng -r _ u· ed,

,~ dire - at aokc I Lent, ~ C . 'I Ill, ,I H ... P inte tOI 'Iring. in the sl ., .. $.,2 stac - ~OJ

S. Stal'tin~g from the queue .,h header of' Exercise l, create a 61e' named que:ueADT ~h that dianne's the following IQueue lyp :

typ,e,d.e.f 8t_ru.C~ qu..eue~type *"Queue;

qne·u€!_t.:YJ?~ is an Inccmplete stmcture typic. Create a f le named queueAD:T ., c that CODrains the fu ~ III de,tini.tion of ~eue_ type. as well as definitions 'for all the functions in queue . h,. Usea fixed-length array 10 store the items in a queue (se Exercise 3{a»)" Create a file named queu-eclien,t ,. c (simihu ItO. the B tac.kcl i~nt . c Jibe of Section ['9'.4) ll..b,alL creates ll\-V'tll queues and performs operations on Ulle111. Be 'SUIle te provide Icr-eat·e: arJtll des'\tr1oy functions for YOIW' ADT.

6. M1fJ1dif, Programming Project S so. lh:ll!~ the hems in a queue' ~Ire stored in 3, tlyn,amical]y allo ... eated, array whose ]'f!l1glh i, passed to 'the Icrela t e. function.

1," MIJd1fy Programming Pmje!lct 5 SOl tha~ the items fin a queue are stored In a ~inked ~is~ (see Exercise 3(b).

You might also like