# ﻿1

~e"

I ,,'

," . .

On,e can only dIsplay complex inionnat,an in the mind.

Lik,9 seeing, mavem~n~ or flc1w or aite,rmJion of view ls ,morS impo·rtanl 'han Il'16 static tJiatu,rer no ma,tta', how IO\fJs/j:

in r' j I • chapn rs we" I see n '.' 0 if ,', '!rl~ n uses of p int rs. Chapt r 11

" b wed ho u' in I, P inter I riabl .' a " fun tion at ~ .. ,I nt nllows the Iunclion modify th ariable .. , hap r I ' ·110' d lot pr ,C, arrai " b~ P '_ rforming arithmetic on pointers to urrav elernents. This chapter completes our coveraze of pnlmers by ~ amining twu atJditiunaJ ap lieations: dynami 't' rage i,I]I" ~ ti In ,aJl p' in'~ , , ~I fun [ii, n~ ~

,ing dynami I It rage allocati 'n" a I-I~ ram i an - in 11JI . k: ' f m In If i,iN D'I: d d during I' scuti n: ecrion '1.1 explain the basics 0 dyDamiC~ l rag allcation .. Section ] 7 ~2 rJi cusses dynamically 'all' , ated string: wbicb provide more [1 : i ilil, than rdi nal _ char ter I' "ra~,' ,.', ti . 17 .. 3 cc d ,nami' ," torag . alll' . uion f r arra , in ener L ,'1- tir 111 17.4 d ~ I vith tl is~ u f :s ora I ~ , I _c ~J]I = cntion=-rel asi I' hi cks of I~;l. nami ally all 'a" d mem ry when the, 'r _ ,[11 I, n aer needed,

D" DtJ mieall- alkx ated struc ture play, _ ' 'i _ role in C p grsmming, I. inc the

an 1-" linl ed t gl ~ ter t - form 1.,1 ~., trees, _' __ . , ther highl- fl . ~bf dah .. tru ture s"

8, nion I 7.5 lo _~ u ~ II an I inke _ 1 L t ' he 11 I " ',-, d ' un [,t link ' ata ~ u' 1_ . _ ..

One af tJ11E: Issues that arises in this se til In-th cono pt of .a "!! I' int, r tc (:1 pointer"'-isli'mpo[ltallt enough t warrant ,3, ':e, 'lion 0" it own (:.llecti,on ] 7,. 'I)~

I ction J 7 ,7 intr du c. e pc int r t I functi m a, urpri 10,1 lv UI. eful c nee : t,

" '\ erful li ,!flar}' functions I expect fun tlon ointen rgu-

rll n I;; -111 " mine lin,' " ~ the Iunc i ns, qaor t., whi 'b i' rting

n ~ ray.

The last two section discus S poin er-relat ed tearur ,~ th t first app ed in 'eg9,: restricted p inter (Section 17,," n fle ibl arra I J ' . me ' . (Section J 7 .,9)~ Till c-' I.' uures or._ pri marif I' fin t r ' tOi td I Ian ,. Ie pr C' I ~ ~, mml - -] "" ,I h th e,c-

lion" can be safety h ',,', i ppe by tru beginner,

413

c - s data structures ale normally fixed in are. For e sample, the nu m ber ofelements in an array is, fixed once the prlogram has been compiled. (In CI99", rhe l,enigth of a

'""a~l~bIB=lenQth ijrrays .. a.s' variable-length aITa,,Y is determined at ron: nme, bUlL i:'~ remains fl-'-ed fOf' the rest 'of the array's Iifetime.) Fixed-size data structures can be a problem slnce we're forced to choose their sizes when writing a programr we can't change the sizes witbou modifying the program and compiling it again,

Consider the Lnverrt.oz'y program 'f Seerion lfi.3,whicb allOIW, the Wiler to add par '~I 'to a database. TIle database is stored in an Bf'my of Length] 00" To enlarge the capacity of the database, we can incre'Hs'c the size of the array and recompile the program, But DO matter bow large we make the arnlY there s always fbe pos '. ibility that it wi ll 51 'I UPI~ Fortunatel y all is 11 0'( lost. C supports d/ynQ", ~Iic' uorIl:ge allucation~·' the ability to allocate s~nrage' during program execution. Using dy .. narnic storage allocation, we can design data, s-tructures that grow I and shrink) as needed,

Al though it's available ~ur al l types of data, dyn,anlic.: stof,ag'ie allocation is used most often for strings, arrays, and structures. Dynamically allocated structures are of particular interest since we CaD link them together to form lists , trees, and other data structures,

To allocate storage dyn~amtif:\ally~ we 'U Deed to call one of the three memory alloca< S t 'dl.ih ~ b:t heafil~r .'211.21 tion funetions declared in the <9 1: dl ib ~ b> header:

~ ma.lIoc=-Allocates a block I f memory but doesn't initialize it. callQY2~Alloc,a,:tes a block of memory and clears it.

• rea-lioe-Resizes a previouslyallocated block of memory,

Of the three, mal Leo is the most used, It's more efficient than ca.l Loc, smite it doesn' ~ have t'OI clear the memory block that it allocates;

When we call a memory alloeation function to request ... block of lnem,ory~ the functi 'n ha no idea Wh,il't type- oJ data we're planning to, tore 'in the bl:o: k, I' ,it can't return 0 poiater tn an ordinary type such as int or char," Instead, the function returns ,BVa!Uf; of type void +. A voi.d ." value "is a, "generic' pointer= esse ntially, j ust a memory address.

When ,[L memory allocation function is called.jhere's alway ,3: possibility thal it 'won'. be able '~O locate a block ofmemory larze enough to satisfy our request, If

that ~. h uld happ 'D, the function Co ill l~eJJI." . ",1"1 pOilJ'I,-,_,~ A null pointer is a . pointer t _ DJ thing '--. . pecial . ali ~ that call be di tin, uishe d F I ~rm '~~H ,', aIid pointers. ~. - ,er VI 1- e ',tor-ed tl1, function', return value in !3 pointer . ariable we must test to 'I _. if ~f.l '. null Pi int ·f.

IC, the programmer': responsibility t test the return alue c f any memry allccati .0 un lion and take' appr.' priat ri a,_ - tion i - i t ~~. · nul] point .. ~., Tb.~' effect of attempt ... ing t ' a ces s memory throu h a null pointer i, .un tlll d: tb_ pregram me Iy I ]~ 1.1 b or b have unpredictably .

A ~,

... -

. he null P 'inter i. repres '0' . d by I' In, 1_001 named NULL ',I ve can 'malloc". return value in the f ][0 ingw y:

}

p = malloc(10000) ~ if (p :;;;= NTILL,,'{

1* alloc'ation failed; take approptiate action '* I

}

i.f ((p= mal10c (10000)) -= NOLJ:j)1 (

/' al1~eation failed; t ake a.ppro,priate action I

Th NULL, rnaeru i' dl lin·d in six headers: eLoca l e . h>~ <s~tcidef "h>,~

(11)1 <stdio., h», '<5tdlib .. h», <string .In,· and <time I.h>. (The '. 99 header <wchar h» ' __ ' ,0 d Im,,~'·, NULL.. ~ ..... ]1 n :' one 0_ th- hurler" i inclu e · , ~ program the compiler Yl'in reo niz - NtJLL~ A program thai uses ,any -" til m m(JfY allocation functions wH1 lneludi <:stdli~~b .. h», of ourse .. making NULL

vaila sle,

In 'e pointer 100 st true' or false intbe same "a~ as number . All non-nul] pointer- test -1U~", only nul], p' inter ~ are fal e. Thus, iIUdL ad of writing

we could write

if (p !. = NULL) F ••

if (p) ....

A ,', 1 In ner c i-'ty 11_"l 1 pre er the _ ~ ~ p li ~ il COl I paris ~11' ith NULL.

Dvnamic storaee allocation i' - cfren use ul for workina wirh strines. Stnnas are

fIif l~ C ~ r~1

stored in character arrays, and l' can be bard ~O' anticipate 110'w long these arrays

need to be. By allocatins string dynarnically \VIe can postpone the decision UD'[H the progt'anl i .. I running,

ma 11 01 c allocates a b iloek of s i z e b.yte,s and rerum - :1 p 0111 ter to j t. Nate that siz;,e_t tY1PIJP7;6 s i ze ha type si:ze,~t~ an unsigned integer type defined if] the C library" Un-~e, 'we': rile allocating ,3 ery large block of memory, we ean just hint o_ ,size a - an ord i nary i n teger,

Using ma Ll oc to allocate memory fiJtr a !f"rin,8 is lea 'Y~I because Ie guarante '" that ,3 char value require exactly one byte Of storage (8i ze:of (char') is ,I ~ in other words), 'To allocate space for a '[ring 0 n characters we'd write

p = malloc(n + 1);

where p L- a Ichar ... variable. (The argument is n + 1 rather than n 101 allow room for the null character.) Th generic pointer "that mall oc returns wiU be converted to chax .. when the assignment b~, performed; FUJI cast is, l1ec'essarY.lln ge'u1eJatwJe can assign a vod.d * val ue ro a variable of any Pi inter - pre and vice \fe·! ~ a, ) Never-

['Ii*' theless some programmers prefer to east ma.Ll.oc ;'1 return value: .

01234 n

A ~

. "hem using mall o'e to ~JJ lncale s,pace for a ·-tri n g dOIn_I[ ~O'f:g:fH to, include mom ~or the n ul ~ character.

Memory allocated u ing mal.Loc lsn I cle ,111 d cr initialized in any w,ay.~- 00 p 'will pointto an unmitialized array IOf n + l characters:

p

[-
~
I I Ii I. III
~ .
~ 1 ,7~2 Dyn,smically Allocated Strings 417

Calling 91 rcpy i," one 'wu to initiallz this arra: ':

4:

n

j
a, b £ I \0 III II ~ Dy ramie '" "'1J",8b·' alloca i n makei i-t p sible t writ funcrion ~ that r turn a pointer to' a "new' strin -a, (ring thatc idn't exist before the. Junction W~, called, Consider the probb m of 'wrjtin'~ Ie function that con at.Mt_ two tring. \ ithout I, han in,\'~ either one.Lrs st ndard Iibrar doesn t include uch 'un "l],,11 I strGat i.·n'l quite what W'B want since i ' modifies on . .of th ' strings passed to it), hut w,: can le- sily . ',ritle OUI\N n~

ur function will m a ure [b Ienaths f the two Iring 0 be . concatenated, then call ma.l Loc t all 'Ieate jut the j ht amount Ilf spac fo-r th II ult. The fu icti n ue t copie th tr u string into the n ' ' sp __ m then call . strcat to cone tenare [be se _'ond strina,

II;,.,>

result = malloc'strlen(sl) + strlen(s2~ + l' i i l I( reBu~ 1: --.. ,N[rLIJ)i {

p'l,-in t f ( n ErrO:ij ~ malioe f,ai 1 ed in concet \n ,,~' e:xit (EXIT_FAILURE) i

ohaz *conca1t i( CO'I1st Q'har .. all COl1:St char ,s2)

{

}

strcpy(result, 81); strEat(~esult, 82); return result:

}

"malioe returns __ null point ~r crmcat; print .an err r me '.' ge nd 1, rminates he program. That's not always th right acti n to take: some program n ed to recov T from mem ry all '''C[ inn '. i lure, . nd . -, entinu run nin ,.

Here's hlow the concat; function migh b. called:

Aft r the' call p wrll point to the ~ tring IIII abcde.f ml ~ hich i .. stored in a dynami. ally all, _ ated arr v, The arravis seve chare ters jl( ng, inclu ling th ~- nuU b" fOB ... ter ia~ the end,

Fuuetions such as concat that dynamically allocate storage must -::e used with care, Wben the string tb:&l,cIDD,(:,at returns is no longer needed, e'Il want tOI I all the f rs IE! function to release the space that [be tring occupies, IT we don - the progr - m may eventually run out of memery,

In Section 13.7- wle tackle ~, the problem 1('" storing string ill an array, We found that storing strings a I -~IOWS in a [. o-dimen ,.laiD· n array of characters can wat te space, ,0 wle tried setting UPI an array of pointers tto. slring literals. The techniques o "Section 13~7 work Just las wen if the elemen "R, of an an-,ilY me pointer to dyruun~ ically allocated II~' ntg'lIl To illustrate thi point, lief rewrite the rle'mind,~ c pro~

'am o IS····Il!:i!i·~~·!O·- 11"'1 1(' w'h"lII"'!!J"'II prims a' DMP -nonILII4..I; t of dail \l r minder

gr·L. . I ·.'~\Cl'I,.llll -I., ..._),~JI~ '.' ,,_I~~, n.n:I!,...Ji :' _ . IU!l,,;-";'[ W ,III I. . ,J .11. ,JLU...Il ,I\.Ii II.

The original rernin,lol, i~J C' ,mJ()igram. [ores the reminder string in a lwo-dinlJ:nsiollllal arr,ay of character r- "wi'tn leach ro'w of the array containing one I. tring, After the program reads ·a day and .its associated reminder, it searches the array to determine where the d~y belongs using at.r-cmp h)1 do eomparisons. It then uses sltrc,p,), Ito Jl10Ve II:U string . below that point down one po Itlon, ~:·Dinl]y~.he program copies the d1~ y int the array and call a t rc,a t to IELpptn,: - lh, reminder '[0 m . day.

tn the new program (re,mind.2 .c I the aftHy will be one-dimensional: 'itselemen I. wi]] be pointen to, dyt:liDoUcaID]y allocated I. trings. Switching to dynamically allocated strings in this program will bay [WOI primary advantage I. First. we c '[II use space more efficiently by allocating the e'KDcL number of characters needed to . tone a reminder, rather than storing tb reminder in a fixed number of character as the original program docs. Second Wile won't need 'La call strcplY to move

.'.' ~ d 0, ... d ·at·:ti· .. · d l' read 'tJI

. . . " '.' _ ~ . I - ,-, _' - -I . 0' ,"_ - , I -_. I . - ~ I'":' "-, -. - - l - - ._ - I . I' "'-1 - , I I' ' :- - - ,_ '.,- , _ I' t I I

c.,X] tmg emm· er mng 111, ore fir to III . ce room or a new remm er, n tea we I

merely 'move pointers to strings

Here's the new program, with changes in bOI,II"-<I' Switching from a two-dim 0- ionia] array to anarray of pointer; mn out to be remarkably easy: we -I 'n only need to change eigblL lines of the program.

#include <stdio~b> ;tine l'ude I<IS t,dli.bl ,.11> #-include <:s,tring. h»

*define ~ REMIND SCI #define MSG LEN 6,0

r- max!,mum numbez ,of remind!ers * /

1* max length of r'eminder 'w,essage *1

Dynaml'cally AI/oes'red Strin:gs'

int main (vai,d)

{

chaE' '*'r,eminderls: [MAX REMIND]:

char day str[3], ~sg str[MSG LEN+l];

........._- ~ ~

in t day 1/ i , j" num r'emin,d ;: 0 ,;

for (i;) {

i,f (num remind ~= ~ REMIND)I {

- -

printf (HI -- No space lefl: - \fl·) ,;

break,

pri tf(UEn-ter day' and remind,sr: II) i sca,nf(ml%2dl"'" &day);

if (,day =:: 0),

hrea,ki'

spri'fitf (day~str, .im~2dll', day'); read line (m,Bg 91 r, M.SG LEN) j

~ ~ ~

for (i = 0; i <: num_r'emin,d; i+ )

i' (strcmp(day_st,r, reminders[i,]') < to) break;

i50r (j = rrum r'emi"nd; j > 1. ,; j - - ) r'eminders [j ] ;: remJ..,ndera [j -1'] ;'

}

Bt.rcpy (r1emind,ers Li l , day:_,st )1; strca (remind,e _:-s [i] ~ mS9..---. str) ;'

}

p,rintf ( ,. \nDay Remi I Ider\n .~) ;

for (. :;;; 0 i · <" nurn remind; '" ++)

........,

pz Lnt; (* %e\n~~, remi~d:ers[i]);

return a"

}

int r1ead line (cha str [] ~ int n)

{

· h!

In,t C_' I ~ = 0;

whil,e (' oh = getchar ( )1,) ,! ~ I \n ~ )

if (i <: n)

str["++] - ch,

strii] ~ ~ \0 II i

ret'urn i;.

17.31 DyaLally AUocatled Arrays

Dynamically alloea ed arrays ]12VC the same advantages 81 dynamieaUy allocated

trings (not surprisingly, since strings are arrays). 'When we're writing a prDgr,&un~ if's often difficult to estimate (be proper size for an array; itwould be more C"OOV'e, .... nient to 'wait nntil tile prlogram is, run to decide how large the arniY' should be, C sol vesIh is proh lern by al ~.()IWiT~g a program. to al locate space for an array d uring execution, then access tJ.le srray through a pointer to its first element, The clo e r··· larionship between arrays and pointers. which we explored in Ch,~p,er 12 makes a dynamically allocated array just as easy to use as an ordinary array;

AJIl\OUgll ma l l.oc can allocate space for an ,W~rl\lr the ca Ll.oo fUIICtiOD is sometimes used in stead " '~ .. ince it Inl tializes the memory [hut it allocates, The r,ea~lo,c function allows lIB to male an array "grnw" UT "shrink" as needed,

We' C,fUl use ma Ll oc 10' allocate space for' on QJT,ilY in much the same way we used

it to allocate :. pace for a string, The primary .difference is that the elements of M. arbitrary array won't uecessanly be one byte long as they arc in a string, As ~t

B.1zeof (Jpe.ra:tDr ~7.6 reo ult we'Il need to' use the s,i aeof operator 'to calculate the amount ofspace required for each element

.. uppose we're writing a program LbJ8Il need .. : an array of ri Imegers. where n Is to be computed during luble eO' _ecutL n of the program We II first dec [are a pointer variable:

.int ~EI,;

IO'nC'e the value of n is known, we"Il have the prD,graml call 'mal 1, Q(::. tOI allocate space for the arr,uy:,

a =ma11oc(n * ,sizeo'f(iu't));

Always use s i.aeof when calculating bow much space is needed for an WT-a,Y. Failing to allocate enough memory can have severe consequences, Consider the following anempt LOI alk cate space lor 1311 array or n Integers:

a = malLoe (11. *' ,2);

I'~~ int value are larger than two by ties (as [hey are on most compuren )i. ma.l Loc 'won"'t allocate a large enough block of memory, Whet] we later try to aCCe8,S elemen .s of the 3111'1" :y~ 'be program may crash or behave erratically.

Once it points to a dynamically allocated block 0.- memory, 'we can ignore the fact that -a is ,[I pointer and u.se it instead ilt an array name .. thanks t . o the relation-

ship b'· twec'n arrays and pointe ", in '", For example we could use the C:olllowln,g I ,p to' initial iz. the m 1 that a p _ lin' to:

for (1 = 0; ~ ~ n, i ,~J a [i] := '0,;

We at, , bs' e the op ion of u ling pointer urithme ic in read 0' ubscripting tc access the elements f th ~ array.

The cal,lcC!: IfunctioD

Although ttr . ma.Ll.oc fun non can be used [ allncat mernory for an array, C provides an alternative=-th ca.l l.oc function-e-that s sometimes b (tier. ca.LLoc has the ' ollow ing p ~OlGtye in < s,tdl ib .. h»:

caj Loc ailJ'caL~1 spa ' for an arr y with nmemb Iements, e· ch of which

B i ae bytes Iong; it re 'turn: a null pointer if the "~.~ UI~ 1'1.'; "p~ ce ISO' t B. aila L'J • . ~ '.cfter allocating the m l110ry~ 'Erallo(j lnitialize ' il by se ling all hilt I to 10., _., ·.r

e', ample the ollo .. ing call of calloc' allocates "or an array I 'fn integer

wbic'h are ' U guaranteed to be ,Z f>. loi .ially:

a ~ calloc(n~ sizeof(int));

Since ca,ll'oc:'lear I the _ml mory tb\at it llocates but malloe do' sn't 'N', 81 Y occasionall' ,_ BAt ~' .. U-,' oa l Loc t I au ca e. pa ~ , for an obie t other' than an array . By calling ca.l.Lcc with 1 81, ii" first araument ". e can all rate space fr -. dar .item f any ty :.

struct point { Lnt; x" Yi } *p;

p = c,alloe (1~1 ,sizeof (str-uct poin-) ;'

Art -hi' statement h been exe uted p ill point '[0 _ structure whos - x and y member . have been ~l to _. ero.

Once we "e' allocated memo 1 tor an array W W,3_ later find th' _ it '. 1[00 lar e or too small, Th· re,alloc function ,can resize the mT _ ' , better suit IOIUl need ~ "11 follo illg prototy e for rea 11Ioc ~ ppean in < at.d 1 ib " h~:

hen realloc' i . called. p,tr mus t point to a memory block obtained by'·~ previous call f malloc c a LLoo " 'r re,alloC!. The sizle parame er represents me O~l . i e of the blo _ k which rm __ }~ be Iarg r . r smaller than the oris Inal siz . Although ~ lea 11 DC doesn ( require that p tr pint to memory thot' 'S .'. ing us _ d as an arra in pra .. ti_ e it u mally d., es,

A: ~

&

.

.

Hie sure that a pointer passed to reaLloc carne fn m IFl prevh us call 01: ma.Ll.oo. Icallo,c.o realloc. If it didn t, .... L Uin 'rl@,all,o,c causes undefined behas ior;

The 'C ,il', nda d _ .. --,. -lIs out ~- number 01 - les _. ncerrung '_ -' I ha ior 10 '

re,allo,c:

•. ' I, 'D it exp d a memor block, re,a,llioc don l initializi the by tie th 'L

• ,- re,alloc can' [ nls (P- the rnem ,ry blo " a· UI:_1 i_ d it rl. turns ., nul]

.-Io,in er: fhe data i the old, memory bt -k is nc haft ed.

If reall,oc: i 'C, Iled v ith a null p inl er as i ma.LLoe .

• H r,ealloc' i" called with 0 as its second argument, i free the m mory blo - -

I ...

_I_,_.'. ,

The Ctandar,d stops short cf specitying exactb b w reallorc W['-. S ill

,- expec it to b reasonably fficient. -,:, hen as _ ',, reduce he sizeo to. mory

bloc '10 r eal.Loc should shrink the blocl in lace," without mo ing the data stored in ·the block. By the s me token realloclboul,d alw ' - - attemp to lee- rpand a memoi _. blo '.k with ur m· vi it, - it's [In - ble to enlarge the hi] :. ~_: (bee I':.e the byte' following the blo k ·ar, Iread in us for ,or ,I' I. I I er purpo se), r,eallo,c, wil allocate a. ne bloi k I,L ewh __ .-_. then . ply h conn nt 011 e old block Into tbe new one,

... like

One- re.alloc has returned b sure 0 updan aJI pointer '! I the __ I_ I ince it" PI, nble than re,a,lloc ha I mOI-: ed the 11,0' .elsewhere,

Deallocating .·.Itorage

ma.lIoe and 'the other memory allocation fU8'Cti()IDS obtain memory blot ks f ,0, r

rage - 001} en own as the lreapl. Calling [be ~,e functions ,- .. "'1- ,n-orl' ki them

for large blocks of memory=-can exhaust til- heap causing the fnnctions to return a null pointer

To make matters worse a program may allo . 'ate bl ·C_·.<I 0' memory nd then lose track of them tb .reby wasting , Ipace. ICon - ider e follov ing example:

'p - malloe (, .. J ,;

q :: mal lOG! (, •.• ) :

p ,- q,r

After tb nrst two ta '_;lnl, nt: hJ __ e been e ' ecuted p P ,~- t - to ole I iemorybk .-'1 while q points ~ another:

p

....
- -
1 p

~

agam,

~ block 'of rn - mory that ,> n '. I'ng -'r c '- c. ~ibl. t a pr 'gam i· aid tOI be ar,b.'age,., ,A progt am that lea e .garbag b - hind ~_. a,' ',~' . RI'O', leak. Sam languages pro' ide a gerb ,ge ,coll,,_c-tor that uto . I,tile'ally In "_(I .~ and reo . 1_·' ga b,u g-"I but C doesn't, Inst ad, Ie' J -'h C pr igra i resp n' ible r Ir recycling it a n g,- bag by cal ing th - £re.e funeti _ n to release unneeded m .mory.

The' :free ~:unctiOD

p ; malloc (.~~,) i" q ~ mall oe ,( ... ,~,)I ,; free(p);

P - q"

~ " if

Callins fre,e relea e~ the bl ek f m rnory that p' in '0. Thi: bloc is 01.availabl e ~ -~u'e in ubr .' c_ .: uen call f mall 0 (}!. or' ther m . mary a lloc ti . n functions,

The rgumem to £r'e,e 1111U t b anointer d I wa . pre, iously returned by a mern .... ry alloca ion func tion. (The argum ntmay al I be ~ [IuD Pi!' in:r~ in ~ ,hieh c I."' rhe call of fre'e It'D: I effe t, Pas sing fre',e ,3 pointer to any . ther obj et (such '_J .. ~' variabl or arr 'I)' element). aU"1 ' undefined behavior,

Although the f re~fefunctiIO'lrn, allows us-to reclaim memory that S ~10 longer need d, using it' eads toa ew problem: ,dall'glillg'p1oiJililrs .. The call free (p)de,alJocilltes. the memory block' hat p- point .to but do- sn '[ change Pi itelf.: we forget thai p nOI longer points to a vall I mem 'try bt ck, chaos may ens lie:

char *P ~ 'malloe (4) ;'

strop'y (,p" II abe ~~ )< ;

Modi-fying the memory that P points tOI is 18 .' erious error, I. inceour program DO Jonger has control ofthat memory,

Attempting to acce~s or modify deallocated J:lle,ll'1ory block cau .. I .. undefined behavior .. Trying '£0 modifya dealloca ed memory block is likely '~D ba, e disastrous consequence " that may includ a program crash,

Dangling pointen can be hard 10 spot, since ev ral pointers may point to the sam" hloel of' memory, When the bloc -. 'i - freed all the pointer are left dangling,

Dynamic storage allocatirm i ! e peciany useful for building list '1 tr e 'I graphs, and other linked data struetur .~I~, We!ll leo at linked lists in this section: a Idi.slr:U~UUOD of ot her linked data I truenrre is beyond the scop 'of till, book. For mar info rm u'tiOIH" consult £1 book such as Robert Sedaewick': A1S'fJJ"ithn!s Ill1 C~ Parts 1-4." FUIl~ damentals. Data Structures. Sorting Seal" 11' lng 'I' Third Edition (Reading, M,asi>'~ Addi ~Ion-we· ley"~ 191918).

A 1~_"N1k6t11i&.t COD"m ts of a chain of structure (called INo'dell),with each node containing pointer to the next node in the chain:

... '" I. ~ V
- ,_ The last node '~n the list con alns a null pointer, shown h _ e s a diagonal line,

In previou chapters, w' 've U Jed an array whenever W'lE: Vie needed to store a ccllectien of data items: linked lists give U an alternative .. A linked ji l i 'more flexibl 'than, an, array: W,' can easily ins en: and delete nndl. in a Hnk'ed list, allowlng 'tb.e, .IIl t to arow 811d shrin as needed, 'all the oth (' hand, we lose th . random access ,~ capability of an array, Any element of an array can be act) ',5 ed in the same

I_I ...,..

amount of ti n__]e~ a c ',; sing a nod in a linked list is last r m nod _' i,,' close to te b, ginning of the li, ~ slew if it ',~ near th end ..

Thi secti n describe how to I, l up 'B. lin '.I,d U. t in _ . It 81',0 hows ho to P [" ' rm everal ' ommon p, rations " n r iliad UOc'L! in, _ 'it ,b a 01 de at the b, ginnin ~ fill li t, searchina or __ node. an d ele tin I .a nod I

1l ' I Up' a ij nked ]1 r'l th, fi rs i th i ng we ~I H ]1, d is a true ur that repre ~ .ent a, Inole nod, ill lb, list, "r sirr pli_:'rul,) ~ let': , . urn that Dod _'- contains nothing but an int" gr I thl' node's data plus a pointer III the next Bide in th J 111 It ' .'r ,7" whs t our n de ... trnctur will look like:

:8, t':LUC t node { int value; s truct node

} "

"

/*d,a"ta at.o ed_ in t:he node 'I /+ pointer 1:'0 I-~e next node */

Notice that dl" next, member ha type 51 true t node .which meau , , that il "all CIt ire a pointer to a node 0' truetnre. There '. D thing P ci,al,ab, ut til ' nam _ node

by the way~wt' jus l an ordin '. tru ture tag.

One aspect of the node structure · er . ,. , neei j mentis 'D. " Secti D 16~~

xplained w, n, rmally have the option I,':' using either H lag I,' r a t }'Pledef name to de fine a nam fc r _ . p rticular kind_, f ' nructure. H w, ver, - 'b. n a structur ba" it mle'm 'e' tb I point, t the am: _ kia ot ~ nu ture, ' ode doe ~ ,- e'n _' equired to

u' a tructure r g. < ith ,u the node ,~g e'd h 0 declare the 'yp' u

riext..

N -_ that we h ve th, riode true ure declare ~"" ~'ll [led '. way tc teep tr C,'

, '_ "b, fl, the U' t begins, In "tblt words, we'll ne d -aria i,ll, that al a, spoints t ','

the fit t nod in th lise L t, .' arne the variabl " f1rs t:

Settina first to NULL iJl~ i'C3'ID ' that the Ii l i,' initiall empt

As we . on" truer a li m ed ist en,. nt t, "r_'~ te nod n b om ~I addinz 1,- aeh t '

Itb Ii ,,' ~ Crea ing " D ' , e requir tbr :__-II! ' teps:

I., All I _ ,te rnemor- for 'the Or"J" I,.

,.::lore d· ta in the node .

. - ',. ms ~rt the n de int th li It

,"U c ",In, , n trate on '(he fir L two sr P for n )w.

n .' I, e teo a nod 'i we ~'U nee d 'V: ri' bl -~ that can point to th no-die tin .. porarily, u "] if' been ~ nsert dint I the Ii" t. Let " _ all . , varia ~IJe new node:

,strulCt riode new_node;

42'-6

0_-'1

We 'U use ma.l l.oc to allocate memory for file n ,w node, saving the return alu in new node:

n,ew node now point

,.._.,

structure:

new node .- ........._-.t

Be careful to, i ve ,13 i z eof the name of the type to be allocate d not the name of a p,(Jii~ ter to that ty 'c::

The program will ' till compile bu - ma'l Loe will allc cal, "nl- enough memory _ 'r ,apOli,Irtter to a node structure __ he likely result is a crash Iat I: when the program attempts -,I tore data in tb nod, that new'_n,ode i ~ presum at J,: pointing t.

('*'new' node) ",value! = l[l;

-

new node ~ -',,"I 1 []

1\1 'ext:;

10 acces ' th val us 'ml er f the nod' " I:_ _ '. plie ., th indirectii n I " -_ ~ ',t

.* (to reference the tru nu to which n,ew~n'olde points). thea the sele lion p, r .. alar ~ , to select a m rn ~ er sfthe " trueture I. 'Th'- par-ollie- e: 81' und n,ew_Dode

e mandator- because rn"e op rator ,.' auld otherw ise alec pr, cede nc ver the ."

t~,e of opfml'ors '»-A,ppandix'lI opera "lor.

Before _ 'e go on 'to the next ~ tep in serting a ne· node into list. ler's take s I

mom ~ nt 0 di U"" a _' J cc 'ul short ut, Ace a rnemb _ r I. ': nre u ,in. a

poin ;er L, so OOD1JIln thai C'1,r I id 'c '9 . pecialop erator ju t for this PU'11l0 0.'. Thii operator, known ag'-"'Il .. '- fU,:O!'.- _~ tiou; i a minu sign foil, we' by>, Using [he ..... :;:. (.per- tor, we can " rite

new node "'" :;.va~ ue ~ 101;'

,._..

I( - o,e'w node) '. v:a1 ue = 10;

,..,,_ -

Tb'~1 ..., > opera ur i combinati n of tb ' '* and ,,-pe - to ' : I p _ nom indir cd, n on ne'w_nod,e to J' __ ~ - tb ' structure that i poinu tc then sele the value mernb 1" of the structure ..

lv;aiues'''4,a The -:> operator produce an lvalue. s I ,~ t: 'D D' _ 'it whereve ~ an ordi-

nary variable would be allowed We ve just seen all ex aI- Pit I in which n,ew ....... node - »vaLue appe ,-: on the I ','j side I-f an a signment, It could JU:',

", a' ily appear t a alii,", scanf:

Notice that the &- 10 e ator i'l nill ' quirec even though ne~_:_node i .. a Pi inter , ithont the '& we d be P' ssing ,SCB'nf tbl - value of new n"ode~>value, whih has typ ' Lnt.,

001• ! of the advantage 0' a linked list i-that node, can be added at ,any point in the' lit: a the beginn 'g,., at the end, or a y her -= in the middl '., Th be. innin of a list i th ' e' ·,ie';t plat ,'- Ito in" ert a Dod, ho eve -,~' ,t t' 'I CU.' on - h ,t C'- ,~

if n,ew_no,de Ii - peln ing t i the n ,I~ e '[I b in ," rt d· II - first M, Pi" inting ,

tbe first node in th· link ~ d list, then c_ J I U ne d · '0 .' atei ents l ' in err the I.

into the 'II,\. First, we 'll modify the new node ,- next; rnemn - to, int Ii', the no I that was previously at the beginning of the Ii· t:

o@w_node - >n.ext. := f iriS, t i

Second we'Il make fir',st point to the new nod, :

ill the _ tatements work if the list i mp ,~ ben we . I e -- node ., 'es

fortunate 1 y. lb make ure thi: i- true, let " tra _..'_ the pro .,~ " ,'1' i ' .. erring . - nod into an empty lis t, We -, II, ins ert ,I Dod -' containing the numb 'f' ] 0 fil~' t follo ed by a nod =- containing 20;; In th ~I figures that faUow null pointers ' re shown as diagonal line ,.

,firs,'t = NULL.;

fJ.Ist

new node :::;: mall,oc (ei zeof If ,sn:::ruc n.ode);.

De · node

new node->nex- ;;;: first;

to

first ~ ne\il_D,ode~

-

10/

ne nod

,.,.__ -

.if
/ 1D

,

/:20 10 V'
~~ n~ od

new node~ ~,nex,t - ~ ir,g t ,;

i rs

-

,1l 20 'tol/

»: 20

10, erring at n de into a Ii nked li .'. t i ncb a common IIp ration that Wi ~ - U probably \! ant to writ ,'I - un ion ~ -f tt at urp "I_~ Let' " name the I meti n add = t.o ~ lis,t. It will ba:-, e twop,ar,am eters: 1 iet (a pointer to the tlr'il node in theld U,-t) and 'n the integer l ,.' '- t red in the n - w n de),

struct node "add_to~lis,t (s,truct node *lis,t, tnt n,)'

{

new node = mallol'c fsizBof (,stru'ct node l ) ; if (ne,,_node== NOLL) {

print'~ ( II Error: malloc.failed in add to_list \uilll )1 ;' exit ~EXIT P:A,ILURB);

}

1''75-

r .:

42"9

I~:__:_.

ne'w node-:>valu,e - n;

-

new node->next = list;

rleturn new~node ,;

}

Note that add t.o 'list oe n t m j~~ the list pointer, Inste d it fl, tum~ a pointer t th _, 11 wlv erean d Dod ([II' at the beginning of tb -' Iist). " bn -, e ' ~IH add to list~ we- H n d to stoi irs return value into fir'~rt:

first ~ add_to_1ist (fir.;st, 0, i first = add to list" irst~ 20) 1

The stat _n, ms ad - n· d '" contaiuing 1 O_.nd 20 ': the -",,' pointer r ,I b' fi.rst.~ Getting ad.d,_'co_list I update first directly ratherthan return a new value for firs t" tum- out t be tricky, le~U return to thi issue in Set ti- n .~ 7.1"

Th ~U' ._ina fun U n u ,'~. add to La ac to - ate s lir ed lis __ '0" inina

-

numb ers e ' __ red bv til us er:

{ -

s true t nede ., fi.r,s t -= NOLL i int n;

prin f ("EnteI a sertes of' integers (0 to 1:E'rminate);. III}; 'fo,'r I{;:;) {

acanf ~""'%d'l! t &:0). if (n -- (])I ret'urn first;

fl.r,s,t· = add t.o 1 Lat. 't 'i ,St, n'l ,

- ~

J

}

Tb numbers will be in re erse order within the " the nod -: _. ,n ainin = th_ las nu - If entered,

Once w I~ Ire, ted ' __ linked It1, m I nee I .. eareh it fo ,a particular ,'I _._ I _-

data .. Although a wh . 1 e loop can b u '- d UJ search a li ~ ~I the .o r 1_ tatem ~nt i '-I often superior, We re accustomed to using the f,or statement when writing loops that jnvo,~v counting but it Ile: ihili - J makes the or' tarement suitable - 'r oth ,~r

tasks a" '-U in zludin n lined Ii -l ~ , 'er I, th usto ary . _I' t

" " it tb ' n die in a - inked li --t usia PI, in er 'ariahle p to ke ep t a tof th . "cur-

rent nod :

p := p->next

adv, nces the P pointer -~rl m one' HOOle to the next, An assi nment of thi -, form i invari bl U I d in t wlu n 'v ritin I . lo P Lh t _ c ver s a linked ~i ..

Let's rile a function name - aee rch _11stth,'t '.: ~ -ehes .Iist I P toted ro by the parameter list) f., r an integer n, i" find n, 'Se,ar.ch list ill return

a point r to the n .-1" - ontaining n: othe wl it win return I ull P nnter, Our nrst

ion of h 1· 1" th " , I idi

ver ,ton 0 s·ea r e ,._ is t re res on ,_'._ ", .!~. t-traver '1·1 l t . 1m:

st:ruct node *sea.rc:h_list (at.ruct, node *list~ 'knt u)

{

for (p -:- list" p ! .... NULL!; Pi - p -,:>next)1 · f ('p- »va lue == n]

return. Pi'

return NiTJLL;

}

f course there ar many '. ther way' write seaz'ch list., On ahernative - ould be to eliminate the pi v iable mst a usin ~ list itself (] ke p trac 0- the I urrentn de:

at.ruct, node *seare-h_list fstru,ct mode *l.is,t, int n)

,{

'fQr (~~ lis,_ 1= NULLi list ~ lieu:-::-next,) if (list-~value == n)

rleturn lis:t;

return NUL1L ,i

-.in·, list. i' '3, .'. py of the orij inal list pointer there" I 11 I harm in changin ·i. wi thin the function"

.- 111 the . ter L i: 0 combine the 1 ~ s,t- >val'UI8 lis !, = .NULL, t st:

n est " ith the

st.ruc't node 1ts_earlC!h list (struct node *lis,tJl in,t n)

......

(

fo I( i l,is,t I,:: NULL && list.~ >valu~ 1= n i lis'_ = list.-:>next)

re'turn Li.st r

}

Since li,s,t is NULL If WI' r aeh the end 'of the list, returnin lis i c' rrect ev n if w don t flnd 11., This 'ersi 11 of ,sear'eh_lis_ rnigh , be a bit . 1 ' rer ;!. used 10·. while statement:

struct node *search 1ist(struc- node *l~st~ int n)

{

while (list ,! ,= NQL:L && 11 ist->val~e != Il) lis~_:: ;: list->next,;'

,re'turn lis:t;

}

1'7'5

I' '",-,> !II11~' ',"

431

A big advantage of' storing data in II linked list is that we can easily delete nodes that we no longer need .. Del ring to, node, Iike creating a node, involves 'three steps:

I. Locate the node tu be deleted,

2,. Alter the previous Bode '90 that it ub:yp~1Jis.es.-~' the deleted Dod ... ),. Call fre,eto reclaim the space to cupied by the d el ered node.

Step I L~, harder than it locks. - _." we search the Iist in the obvious way. we'll end up with a pointer to the node to be deleted, Unfonunately, we won-l be able to per= form step 2, which requires changingthe prrJl1tfJl~~~~'" node.

There ar-e various solutions to, thi problem Wi: '11 use the "trailing pointer' technique: a~ we ,- eareh the list in ... tep ~I t we "11 keep a pointer '~O thtf: prev ious node (p rev) as well las, a pointer to the current node (ouz'). If 1 i 6 t points Ito 11 ,e li_ t to be searched andn is the integer to be deleted.jhe following 100p implements step

~ :

f'olr (cuz = l_i e 't ,p're.v - NOL:L;

(l'u,r != NULL 1&;·& ,cur .... :>va:lu.e 1~· n; prev' :~ ClUJ:, cur' ': eur-e-next.l

!

Ii

Here we see the power of C"IS for' statement, This rather exotic example with its empl~y body and liberal use of the comma operat -"r. perform, I all me actions needed to, search for n. When the loop termin,8'lles, cur point to the ,DO de to be deleted, while prev pO'inL'.:i tOI the previous lode (if there i one).

To see bow this loop w·orks,. let's ,asSUID:1e 'tha·t list points to Iii Ii t containing 'JI·O ~~o·.·· ?IIO·· ,. - d 110 · . tb . t· ~d-·-·:·':·

~ . - ~.Iii ..... '- an ... ~, III . III 01. ,e.r~

.- -Iiio _]g .. 40 , ... ,20 - .~~ 10 [//
, ,_ .'" Let~·.·ay that n is .20"SO our goal is ··,0 delete the '[bird n ··dc rn the I'·, t .. After CUI = list, pr'ev:= NDL.L.llM, been executed ctrr points to the first node in the llsr:

1 Lsrt

0 ---
, ..

• .. 30 ,~ 40 ~
,~ The te t cuz 1;:::; NOLLI k.& cuz .... >v,al ue ! =: n is true, sine cur i· poind ng tala node and the node doesn't contain 20,. Atl'et prey ..._ cuz ~ cu.r « cur'- >·nle.xt has been executed, we begin to '. ee now the prev pointer will trail behind cur:

prev CUr

II
~

J~ 40 --- '" 2Q , ... ~o /
.. lis-t

r-'
,
30 ~
~ Again, the 'let cuz !, - NULL && cur- svaLue I - n 1- true cur = cur _, e-next; is executed once rnor ,,~

prev == C:UI "

p ev cur

,
,..,
~, 'i~
" 30 , ... : '0 , 201 .;00 lOr 71
.-
, I list -~

ince cur' now pints, to' n no- .. omaining 2J, the condi ill cur- >val ue !, = n is, false and the' loop t rminates I

Next, we'll perform the bypa" t required by sn 'pr 2,~ The statement

makes the pointer i"D the pr' vious node P 'illt 1'1 the node aft 'r ihe urrent node:

prev cur

list

~
, ,t
• 30 ,0 -, 20 ' ... ,. 10 /
f,ree{our) ;

The ii' n ing functicn, delete~fr'om_list, U" .... '-I ,,~- strategy tn we've jut outlined. When given ~ J1.' and an int .' er n, the function del, re the first n ,·de containin ri, If no node I ontain I ri, delete fr'om list des nethlng. In

,~

I ,jther~'j.· - the function ret rn poult r tc the li t.

st,;ruct: node *d,e,lete. fro'm lis_ ('srt.ru,c - node *li,st; int n)

{

S I' rue t; node cuz , ,pre·;

for (c'ur ~ l].st J p,rev ~ NOL!L;

cur!= NmL &ii eur->valu'e 1~= n , pzev :::: cur, cur:;;;;;: cur - »next 'I

..

:Lf (cur;= NULL.) return list;

if (prev ~ NULL) lis1: ~ list->nex't,i

/' n is in the. first: node 11 I

prev- e-next; == cur = :;.,next ; free (cur ) ;

r,etu:r:n l.ist. i

Deleting. til _' first DO ,e in 'the list i a special '. 'Ia~ .. The' prl9V ~ -- NU,LL tell ,hi - cks for this (;JS .' which re uire I a different -'ypas't"- p,

'When the nodes ", llsr are k pt in 0' dl'r~l. rt,ed hy the data 'ored h I. ide 'be nde",---w 'Y that tb . 11' t i 1·"r,d,Fe,d. In ,e£' in,' n e into an orderec 1;' is more difficult the [1 die - on't always be put at Itt beginning oftb ! III bill, lat· hing Ii .. ast r 1(", _ can ,t -, 1 :, ' i·, • ler rear hln~ h, p, inl at . hi ·~h I he "Hid n d.

'QuId h:a', eben Jo' 'ale ). Tbe i U'Wi'D'D progn lID illustrate both the in __ r _ '_.',1 d d i fficulty of inserting n( de . nd til :t. tster . ear _b.

,f lie I, .11- part I atabase pro I 'am ot Section I .. I~ hi I time i tonng the dar __ "'" base in '_ tinkled list. smg ,31 tinkled list jll1o; tead af an an! oy b: I t -I major ad antages: . I) _. ~ dOD 't ne d It PI~J.J: a pr'~ e I limit II U:1e ize of the datab I. e: i an grow until the s no more memory t ' store P' ~1,~ 1'2.1" re t, I •. n e-, lily, I, P the database sortcd b pert number-c-when , m ' pari i add .. d tc thedatab· se.we ',im~l, in ,. _ l it in L: proper place in the list. In the original program the da,t be 'e wasn I

rted,

In the [\Iew program the par"t structure · ill c ntain all 'cddi'li nal m mh r ta

pointer ,_b- next node l[11 the linked list), and th variabl inventory will be' point. r to the I rst node in til Ii r:

struc:t par {

int numbet;

char name, [NAl4E LEN+l] ,t i.nt Ion hand;

.......

at ruct part *'nex·t;'

} ;

struct part .inventory = NULL:

Mot ' f h functi n . in th< n ~ w pr _-ram ,fl1'1;1 ~',1-1 r ~ ern bl their count ~ rpar" in the original program, I hie' find _part and ins,ert function wiU b ' mcre complc ~bn" ver Inee we'Il k .. ,ptile "d.,. in 'he invent 10 y Iist sorted b nart number.

In the ~ riginal program ~ find _p,art r lW11 ~ an inde int th, inven t.o.ry

rray, In thenev program .. find_part will r ~ tum. poimer ro the n.od that contain ' the, ,e· ired part number. If It doesn 1 find 'he part number, ti,nd:_part will return a null point ]~. Since [hI 1nvenc,oX)! li ,t is sorted, by par numbet the new ven jon of fi.nd_:part can sa e ime bl' ,s,toppin:g its search w.hn it finds ,a node

I ' ntaininj it part nurn . er that" greater then or equal to the de. ird P'aJ1 number . .L.ind_part, search loop will ha e the form

flor I(p :; inven,tory;

p ! ~ JlllIliu &,& nuUlb'e,r ~, p~>numbBr, p - p ... snext.)

Tlu 10 ,I,P will terminate when p b ,0 me NULL I indicating t118t the part numb r

wa n l found I ,'. r wh: n number ::> p- »numbe r i fah e (il1.di ating that the -parr.

uurnbi r e re looking or j, I,' " than or equal to a number already stored in : nod '). In tb t· tter case, WI "~tiJl] don 1 know whether or not '[be de . ired number j ... aetu -lly in the list, '.0 w', '"]] need another te st:

if (p' l ~ mILL && numhe r ;;.,.= p= '>numb,er) r,sturn p;

The original V,5f],OD of i:n"sert stores 111 new part in th, next 'WAil ble ,rlr[ .Y element. The new version mU;'1 determine wh re the new part belongs in the list and inert it there, . e II als , have ins,ert checl whether the PIa: - number i,. already pre, ent in, the ItJ. ins,ert can a complish both . ski b} using I_ loop sim-

~J 11.., ., f:· d

tlar tn tne one m . :~nl-'_p,art:'

for (c:ur-, inventory, pzev ;;;;: NULL ,i

car ~.= NULL Ed!: nEna node- >number "> leu = e-numbe r ; pr'9v = cuz , our = ~ur - >uext )

r

Thi -:,100 I reU" . 011 two pointe r s: cur" which points to lb - current node I' and prs:V:r

'·hL-h point to th . pre 1:0U' node.Once the loop tenrunates io,sert ,- ill check whether cur isn't NULL and new~n,ode'-:>numbej( equals cur->nu'mbe'r~ if 10'1 the, part number i" already in tile '. 't. Ortb_'rwi ',e Lnaez t wilJ in ert a new node

b· stwe n the nodes point 'd to bv pz'ev and cu r usin . g trateav S'llDJ'·' -"'~]Q'1i'" I' " the one

Ii:: II. """ _, lU· "'"' 0::11 . Ii .. " ~.'J ~ - _ ~~, '....... . .~. ""," I ,g.Il. :_ IOJ' . . _.IUd! IL I . _ _ .' '*""

we employed for deleting ,3 o· de, (Thi s strat 8Y WOf, even ifth " new part nnmbe r i larg er than any in the list: in that cas e, el·ur will be NULL but pr'ev will point to the last nod,' in the lis t.)

Her-e " the new program, Like the original pr ,gr-am this version requires the r'sa'd_line function described in Section 16~'1; 'I assume th r re,adline .. h contains a pmtot. pe for thi " funJicbou ..

/'* Mai.n, aana a pazt.s dat.abase (linked, list version.) *1

I" in'clude <stdiol ~ h:> '#inclnoe <::stdlib. he.> inolude IIreadlin€J .h~11

#'define, NAME LEN ,25

s'truct part ( int nurnbez s

ch,ar name [NAME:_LEN+l) ; int ,on_ha,nld;

s,tru,ct part *:next;

J :

struct part *inven'to,ry = 'Ntn..L"

/* points to first part *1

at.ruct. part ·fin!d~,art (Lnt, numb',er) ~' void Lnaez t; (vod.d) ;

void search (void) ;

void, update {voi,d' ;'

void print (void) i

I"" "'=' '* * .' .. '* * • '* * *' * -It * * it *' ,., * * "t' ** « * .. *' * * * 'it '* ,-It: *'* '* ... ' ir * - - .... * .' +. * * '* ...... 9.' ** W

* main: Prompts the user' to enter' an opez at.Lon code '*

.. th,en caf La a f'un,ctic'ZI to perfo,rm t.he r,equestled

'fir, action", '&e,peats until the USEl:' ent.er's t he fiT

'* command 'q' ,. p'rint s an ,error mess,ag'e if 'the user

'* ent.ez s an illeglal c,ode ~ 'I:

****'*.******~ •••• *******~*.** ********.* •• ***** *.*****/

in,t 'mai,'n (voidl,)

{

for C;;')' {

p,rint:f ( u Ente'r loperatIon code : ml'; scanf (II %c ml, &C'olde);'

whi,le (g'etchar () 1,= '\n " ) /' skip's tlQ end of line '* /

.

I

It h

:S,'Wl. II en

case

(code) {

II i I: insert ( );' break;

'. s I:: aeaz-ch () ; ,b,r.e.ak;

I U II: u.plda.te ()I ; break;

f p II: P'l: int (') ;

brle:ak; case Iq~: return 0;

,d,ef,Bult: 'printf I( lI'Il,l,egal c,ode\n JlI) :

caae

}

printf ( II' \n II) ;'

}

}

1'* *' ......... '* *' "* *-" ok :* *' .' W' '* 'If: '* * '* * 1:-: 'w #: .... ,~, if **' *' '* * . ;If *,. * -#I; ... '* -* '* .. '* it '* '* "I: *_ .. if '" "* * .. * ' '

* find~a,rt;' L'o'ok,s up 8. part numb_ar' in the inventory *

* li,s't,., Returns a pain,t'er to t:h,e node

'* containing the part mrmbez , if the part: ..

~ number La not fCUIl'd,~ returns ,NULL,~ lilt

*~ ***'It.'*,* **-t'w'i' ** * *'* *'W'**'*'*'** * . ***,*W *.. *'*** .*'** *' .,*** *** it ~,* '*"'.' I

at ruct pa t *f:Lndyar- (in't numbez )

{

at.ruct pa,rt*p;'

for (Pi ~ invento,ry;:

Pi !,;:;; NULL && number 7> p- >nUHiber ; p ~ PI- »next )

if (p != NULL && number return pJ

r,eturn NULL;

}

I**************·****************·****w******* •• ***~*~****** * insert:

*

Pr'omp'tSr nhe user fo,r l.nf,ormation about a n:ew *'

part. and then inserts the' part into the *

Lrrvent.oxy list; t he lie,t remains, Bar't"ed by 'I;:

p,art numbex , P'x1nts an error meaaaqe and *'

rleturns pre'maturely if the part alrea,dy exists * 'or space could not be alloc:ated for he paxt;;

**~******.***~****.***'~*** '.********************.*********/

voi.d insll!'rt (void)

{

struct part *cur, *prev,

'*new riode r

~ -

new' node - mallo'c (sizeo' (,struct par t.) ') ; if (ne"w~node ~= NULL) (

printf(UDatabas@ '9 full: cantt add mo:re p,arts.\n"); return;

}

pz Lnt.f (IIEnter paz t numbex ~ II) ,r scanf (~~%d~'I, &ne:w_'nade->numher) i

for (cur = Lnverrtezy , p,r1ev = NULL;-

cur !;;;;;; NULL && new node - »numbe'r :> cur- .numbez , prev == cur J cur -- cur- e-next; )

if (cur I, ~ NULL &.& new noda-c-numbe r printf (~~Part alr'eady exd at.a , \nll) ;' f'ree '(new~node) ;

{

,return,,;'

pri,ntf (~'Eln,ter pazt; name : t~) i r'ead_linie (n!ew_D,o,de->n,a,me', NM4lS LEN)I; printf I( UEnter quant.Lt.y on hand: m~) i aoanf ('11 'd'll, &n,e'w node- e-on hand) ;

- ~

new node->next = cur;

-

if {p'rev == NlJLL)

inve'ntor)l == new_node';. else

prev- ~,next ;;;; new node,

}

I*·***···~~··**·k •• ********.*.** •• *.**** •• **.***.*****.*** 'W' searcb'~ Prompts the uae.r 1:.0 enter a p'art nutnbez , t.hen *

'* 1100k~, up the part in the datab,ase ~ If th,~ pa.r"t *-

* exis,t,s,f prints the name and quantity on hand;' 'W

*' if not., pr Ln E;S: an lerror message·. '.

*'Ii .t-*= •.. t:+,**,.,,- ****'~,***' **'k. w'ilf , .. **",~****- .. *,:;t' ' •• *_"*"1;*. *****/

'void. ,5learch (VQ id)

{

int, nuRilie,r"

- . _ v- 'I

s't:ru'c't part *Pf

prin'tf (lI'Enter p,a,rt nllmher: 11): scanf I(' lPI! '%'d·nll~ J &n,uuib~:r);

p = find __;p art: (nu~,er) ;

if (p ];= troLL.) {

printf ( ~~ Part, name, %,s'\n 1111, p-;..n,ame); pri.ntf(~IIQluantity on hand. !kd\nfll, p-:>;,an~hand~~'

~ e.l se

/***** •• ******** •• ********* •• *****.****** •• **.** •••••• ****.

* updat e , P.j['ompt:s th.lE: user to e'n'~era p.art. number ~ '*

*' p'rin,ts an error message if the p'art doean I·t 'It

'w exi.at , otherwise t~ pzompts th:e user to enter if

'* change in quan,t:i!ty 'on ha-nd and updat.es the '*

''N Qjatabase" Ii

*****.~~*.******.*****.********.****.**'~.***** •• * •••• ***~I

vo id upda.te ('void.)!

[

int number, change; ,g'tru,ct: ,part *p;

print.f (uEnt.erpart: numbe.r : I~'; acanf ( I~~ %'d ~III ~ &number);

p ~ findJh:lrt '(numbe.r) ;

if (p ,~= NlJLL) -{

p.rin t; f ( mm Bntler change in quan t i t:y on hand : 11') i scant ( 'II %d.II" &!,c'han,ge) ,r'

p=>on ha.nd .t-= changle,;

} elsie

printf (mlllPar't not fou;nd.\nmm);

I*****·*******~*******·**~~kt**.*.*.*.**.~** ********* '****

* p~int: Prints a l~Bting of all parts 1n the database, *

Irk' shot'wing t.he p,a.rl: .number , part. name., and ..

* .qu.a·uti-ty· on hand .. Paxt; rrumbe r s will ,ap'pear in '*

'* as,c@nding a'rder.. '*

*** ~ ******,****,'*****w' vo i.d pri'D.t -('void)

{

at.zuct; part

4-a-8"

I: .

1-=' :_

P -in'cf ( lim r?art. N'unfuer Part Name 'I'Quantity en Hand\n"') ;

fO.r (p ~ invent-ory; p != NULL;p :: p->'n€!!xt)~

printf ( II ~7,d '~25s~ 11d\n II, p-:>nll1l1ber; pl~>name"

p,~>on~hand) :

II

}

, ticethe U'- 011" fr'ee: in th insert un -(no Lnaezt 1',lI car e " rnemor for: pun before checking to see IT th pall already c··' "IS., Ifit d(1I:S in~et:

D dease the 'pa1ce to avoid a memory Ie ..

III " . tlon 13. 7 ~ we came ICIO~'S the notion 0 "a pointer to, .pointer. In thar ~-. ection,

re used an array whose elernen . were (1' type char *';, pain' _ l~ . ne of the arra, element itself had t p char 'k *., Th, - I C n:_ I =pt .... - poinrers t p- int _T ,,~ I I .0

pop~ np Ire uentl_ in th _ nte t I-, • linked da ~ .suucture ... hi parti uls r vhen an argument ~n 13 fun 1', ,0 is :1-;1 n er va .' ,bl,' ~ w' ' H ,I iometimes want 'the function to be able to modify the _otiabl,e Ib,Y makins it point somewhere . else, Doing 10>, 1 requir . . the u e of a poin t ,'r to a p iinter,

COl I dder the add tOI 1 ;-,srt un tion to "" Section 17 .5~ hich inserts a node at Ill]',. beginning 0:' ,a Hoke' lit-ben WI£: calli add~to list- 'e P' it a pointer rc the first n de litl th origin 11 llst; it then re tum a p inter ~ Lh lil'lt nd in the updat -d list:

struct node * a d,d_to, list I(Slt, 'uct node li.s,tJ int n)

{

aeruet; node 'ltnew_n.ode ~'

new~no:de .= malloc (si'ze.of (struc,- node)) ,i if (new=' node =~ .NULL) {

print.f 1(' '~'Er'ro,r: mal1o"c fa,ilea in a.dd_to~list\nflll ;' exit (EXIT_FAILURE') ,

}

new node->value ~ n;

......

new no,de-':>nex:t ~ lilst;

return new~no,de;

}

Suppes th,at I, e m di y the function .0 rh t it issign ne'w_nod.e [ list instead f returning new_nlolde" In otber wor .. let'Ni remove the I"leturnlwt,eJ- ment from laldl:d~tol_list and replace it by

lis't. = new node;'

~

Jnformnately.rhis idei '(J.'1I"t I OIL Suppo U,'!W- call add t o l~stinth, f llowing wa, ':

A the Pi int . f th . C - - J_ irst is c ~ to Ii·st. Point rs r __ e 11' 211mnt,

,'-'

" '. I - a sed .' alu ,,) The I ast lin in the _- nc iOD change - the D· 0"& 1 is

iDo it P int to th I I.'W nOI e. _ - "'. 1-"1 gnment doesn t affect first!! hov e ·er.

Geui -g add_t'o, __ list 0 mod c f; rat i, possible, but it requires passing add to_1 list 3, pointer to fir,s,t .. Here ", the corr ct ver i n 01_ lb, fW1Ction:

void add to list (struct node **list, Int oJ

-- -

{

stru,ct riode *ne r., _n,ode,;

I'llew node ;: ma l.Loe (sizeo, I(SlltruC't riode l ) ; if l(nle't1 node -= .NULL) {

printf (IiError ~ malloe flailed in add, l:o=list\n"}I;1 exit (EXIT~FA1LURE;) i

}

ne:w' n,ode- >valuie_ = nt'

...... -

new node-~next = *list; *list =- 71,ew_ncde;

}

,_" hen . 1,- aU til D,_:_ versi n . ;a,dd ....... to list th fir -I arg - rnent

a ess of f ir,st:

Since li,B,t i, assigned the address of first'~1 ' .'~ can use *list ~L, ] . lia I for

firlBlt~ In part; ui' -- assignin] new node '0 ~ - is:t - in m,odif- f Lz at ,

We .. ,en that peinn I m_H,' P sin arious .kin··· ~- includim variab

arra elements and d· amlcnlly allocare block: 10': memory, Bu C doesn't r quire hat pointer point lanly I data; if's also peel ",i le [ have pointer tc functlons. _c'ointer, to functions aren't fl.' odd as YI(lU migb chink After . unction I occupy memory locations so e ery function hal an sd '1', ju n as each ariable

has an 1_ .~ d 'S,.

W an u e function pointe -_ ~n much lb" same ,- US 'I d' It:·~ .• In p - ti·· nlar, P" in a functi on p •.. mter 81 I argume n i!' .. tairf I ommon in C~ "',UPP"IS,C that we'n 1 ritins a function amed i.ntegr,ate· that integrates a math ~matil;al fun lion ;_ DI point and b, -, 'd like to make iu,t,egra . e as general at' p , sibk b1y pa1 ~,~lIg i fa an argum snt, To achie- • '[hi: ffect in C ,I we'Il declare f to be a poinn ~ to a fuOICli'DD,. Assuming th~ It we want tOI iJlte2Tate function that have

" doub.l.e pan meter and reru '-1 douh'l, e r _ sul t, lhe prototype for int egra t e - -ill look like thi :

double integra'te (double (*f) ',double) t, double a, double b) ;'

Th pj J entbe ses '·~r un *f indi " [- tha f is ,_. poin ier 0 a fnneth n nl ill fun f ·n lhtllt returm ,3 pointer, It's al n Ilea, I [0 die. lar "f as thoug h it were a function:'

doubf.e integrate (doub l e 'fl(d,ouble), doublle a , doubl e 'b) ;

From the compiler' - .. taod eint this _rotultyp is identical to the previ U~ ne .

. -tl c· n in egra e"'!ll~ npp~ '~I. functi 'In nam ~ the fir ,,\ __ rgu-

sin unction "23.,3 rn n . mpl ~ th fa,]] . - ing call "il inte elt th sin tine fu -tioll' . un 0

to ftJ2:

reBult = integrate(sin, o.c~ PI 12);

. otic' that I here a e DO parenthese I after a.i.n. W11en a fun ition name' i It t :IS 1-

]'OWI d by P" Ji D hes '.' ~ th·. ~' am pil r pr ue , pointer tQI be function in ead of

generating cod. fOIf a func i n call, Inur I', ple, e r ~ not, ailing sin" in tead

we're pa'" ine integrate I~. pointer 10 sin. Ifthis "/_', n1-\L confusing. think of how C han ill e I aIT'1Y • a l til ru I. 'r ~ In arr __ y ~h· n a [i J .repr ~" n :n - el ment of the array while a 1"1 i' self I erve I _ p. inter to th arra ~ In a simil " ay, .if £ i a function Chi'. t f (x) ,.' " . eo III of the ' unction bu f b;-J its elf ". . ,8 poi nter to the

"unti n,

Within til, bod' 10' integr'la.tell· e can call the unction that f points to:

'It f I" _ present he fuoc ion that f points '[I I~' x i I tb,. ' argument to U11~' call, I'hu duro. ing the ex senti n __ intelg'rate (si.n I 10.,0, PI I 2)1 ~ each call *f i , "._. 111.I'll, a call of sin. As an all mati' e t '* f) (xli - C all '. u: _0 ,-- £[te f (X)I to call [be function that :f poi nt~' h. .' llhough f (x) [0 I rnor - nt tural, I'Il ~. tick

ith ( .. , ) (X)I us . remind rthat i if P "nt_ r t D fu ction, [1, I function name.

Alth 10 - h i might eem thai p inter t. fun ti ns s en t relev am '[ I the a er 'l~e

programmer, lb- t I ' uldn 't be further' fr nn th truth! In ' at, om IQf rh . rna 1 us e ..

rut n ti I.n ill. lh C library require a function P oint er ,8 3D argument, One 01" the _ is qsort . 'hi.11 belong t the <stdlio .. .h» header, g,sort ~ ,_ generalpurpose sorting function that I capable '. f orting any . :ra~·" bas d on any criteria

hat . e I -ho :'1 "

:10'1 . he elem nt e am y th' t it orr rna J h ·0 _. typl e en It rue-

ture O~ , union type:-qs.o·rt n10'.· t be told how l .' d terrnine which of 'two ,array ele-

. en i' -'1L11ali r, - I "ll p 1.'- i " hi inf rm ti n tQJ qao.rt; irin a

, OIl'P,dris'OR' fl",,/;;lio'll~, Wh~D gil _ n t -. pein er p and ,q t array _ lemen s, the omparison functi _ n [nut r turn an integ r th .. t i:. n, .' tativ; If *p L, JI··S mao ~ *q

zero if it'p's "equal o" *'q" and po,lIjl"111 e if *p ls "sreater than" =q. The tenn ' "less 'than u "equal to," and "greater than ure in IqUIQt_ . because it' ,OUt re ponsibility to determine bow *p mid * q eve eo,- - par - d t

qs,ort bas, the following pro otype:

void. qaoz-t (vo.i.d *base, si-z:e_.t nmemb , siz,@ t siz'e,

int (*cO';lJlpar) (canst votd '*, canst void .});

b'aL,se must point to the first element in the array, (If only a portion '0._- the array i to be s rted, - , e U make ba IS IE point L .. 'the fir reb me nl in thi "~. portion. ) In' hie ~ rnplest case, baEH~- isjust the Dame Olf'lh arra . nmemb : .the number of elern nt ' '0> be sorted (not neees nrily the number of el. merit on the array). e;i 'Z@ i_, lh - '. t. , -, of each array element- measured in b,' tes, cornpaz ", a pointier to th - '0 pari ron function.When qsor't: is called, it sort', the array into ascending order, calling the cornparisen function whenever it needs tOI compare' array el ments.

To sort the inventory array of Section Ifi3., we'd use the following call 0 r' qsorc:

N otice 'Char the second argument i ., num ~art s not M1\X_P AR TS: we ' ~.on'~ 1 W3J11 to sort the entir inv,e,ntory array just the portion in which part __ lle urrern ~:~

I tored, The last argument. oompare ~arts. is ~1 function that compare two 'par't~,i:ruCllJrIC .

Writing the compar'B=par1 s functi 111 i n' >[ easy as you might expect, qarrrt; require [bat it, param l· r h ve type void .- .. but we lean t access the members of a p,art stru nure througb avoid .' pointer: we 111 ,d ,. iointer of type struct pale't 'IF instead, Too' e the problem, - ~;'IUU have ,compare~arts a ign its parameters. p and q, to variablr .,. of' ypc' strruct; par't W" rh reby con, erting them t the desired type. conpaze ~art s can no U~· e [I _', . ariables '[0 access til,le members of thestructure I that p : d q point '~ . Assumi ng that we, wan" to ort the Lrrvent.orv array into ascending order b,Y part Dumber' here's h w the ,compar,e_.j>art.s function rnlgbt look:

intcompare:_p,arts (cons l: void *pl f conat; vcd.d .q)

{

const; a rUC'tpart *pl - p,; conat; et.ruct; part *ql - qi'

if (pI1-.>numh,er -c ql-:>numbar)1 r'leturn ~l;

el's,€! if {pll.- sriumbe.r ~~ ql-<>number) r'e'turn 0 ,;

@l,se

z etnrrn 1;

The declarations of'pl. and ql include tllle '. ord canst' Q avoid getting awarning from the compiler, Since p and q are canst pointers (indica ing that th _J objecf

442'·'

- - :.

vhich they pein should "[I) modifiedr. fhe should b assizned onl: '0' ointer ,I ariablei .. that are al 01 d .. claretl to, be cone: i.,

Ilb ugh this 'cr in f complare_:__par: 131 worxs, mo 't ' pr -,~r rnmer

, ould write th fUDCH n more onclsely, Fir' ,n, IIC,- that', can r pi pI ''_I' "

ql by Ci;_1 ,t expre: -,ion :

i n't CIQ:mp,arB _part"B (cons t vo.Ld *,p~, cons t void 'It ,g)

l

if (( tstru,ct p,art w) p) ;oE~numbe.r <

It (s t zuct; par It ) Ci)"" ::. nuflibe - )1

r'eturn -1;

else if (, (Csltruct. part *)1 p) -~nut11ber ~~ ( (atruc~'1: par *) q) ~~numbler' return 0;

'el,sa

zet.ur'n 1;

}

The p_ en h ': ' arund ( (,struc't part ) p)~ '_1- n ':'"1 '- ar .' 'with u th m, th , compiler would try to cast p->nunml[er to ty_', st.ruct; pa'rt *,.

_, n _ -'I " c~ompare_Plar1:s ," en sh ,I' er y r 'm:' ving

int compa:re_parts(const. void *p~ consl: void' q)

(

return ((,struct part *) p)1 ->n,urnhe'r - ( (st:L~ct, pa r t .')1 I ) ~ ~number i

}

Subtmctlna 'ql part Dumber r rom P I part numb ,f' pr duce 3. negati r re ult if p

h'" I mall, r part Dum --ereflo if -I -, Pi rt number ar _ Ie, ual ,_: _,_' ,I P',' i · I result

iJ pill", larger part number, N' It '[hut, u btraeting two i oteser \ p tentiall ~ ri sky beau e t tb dr ng - "If ,'e'rfiow. I m a' suming that part nu .. moen

uve on' e T" that sbouldn l happen h re.)

, '" sori the in'vlen'tory' _ IX Y b' part D,:, m instead of part numbe Wild I, the 'ollowing ','II i '10 of cOlmpare,~arts:

int cQ,mpare_parts (canst \lc:Jid *p~ canst vroi'd 'qJ

{

z'e turn ,s trcmp, ( , (s: true t par't *', p) ~ >nam,e " ((8 ruct part *) q)->name);

}

"n co,mp,ar.e_part,s ha '·0 do i all 1St r'cmpt which cony ni ntly r .. turn '- a [L g uive, Z ro 1_ r Pi ,~iti-' ,- resul t,

e-mph_ r ized tb- u e ulne z if function ,in'[l' ", M()WD n I,

I her ilu tions, that's not _: ,U l _ r I s 0 'd for, C trea s p inters to U.DIC ',00;' jus]

- ike pointer I to dat ~, I -:, II stor Iunctiei pointer in ari oles r, _ th ~lDl a;:._ ele-

m n' · ,an IlTfty or :.~. mernbe r of ,3 structure . 'r union, We 'an I 'n write : uno .. ·

lion' that return function point- ..

L lie - r an 1-' amp! 01' a v. _cj abl - thai p in te r 10 ,n _ tion:

'void (pf)'I,int);

pf can 11 iint to an tunc ion -ith an int P' met er " d return ~. pe f vod d. f is such a function we can make pf p ',iJl't tc f in lb_ fuU wing way:

': otice m ~t there's 1]0 ampersand pI eceding I ,i' Once pf point I to f, we 'an call f

b, writins idler

An- YI,b ~e -1 nents are function poin er b __ ' ~ surpn ing nr m I applicatk ns, For example, uppose thatwe're C" riling a program th t di plla~,~ . menu of commands I" r the ll .. er to choo 'frOIID. - e can wilt ,-I functions lha_" lmple rnent these comm ds then I 1 if- pointer 0 tne m li I D in an arra , o'

void I(*£i.le_cmd [1 ) '(Vioid) - {new_cmd,

open_cmd~ close_,cmd,~ close_al~ cmd, sav·E,.,."..cmd,

savle as, cmd,

- - -

aave a.l1 cmd,

~ -

print~C'md;

,e.xit cmd

} ;

If' the user s leer command n wher n,JJ. f i 1 e _ cmd ~lIT.ay and _'aU the ' ~orr ~ ~ p • nding

In ' 0- cr~ .'- tb

(* file_ cmd [n] ) If) ;'

I '. OT file_cmd [ri] (,; *1

Of course, ,. e could ,g~ t a simUar ef eet with I ,Er~·.itch slali ment.. sino an array

fun tion p ,in. rs ~- -e . lI. m re De ibiljL=· ho - eve t- . ince the elemenn L~

',aua.. can b changed ,~,' the PJ!" ram L rennin 'I,.

The foll wing program print t bl - howin ~ the valu . nfthe cos a.i.n and tan ~ma","b" n!!! head'er.23..S: function I, all thn e -1- ng to <ma th ~,h> ' .. The p,r .Igr m i uilt s round a function

named abuLa e. that- r hen pas r a functi 'D, . in, er f. print I ~ able owin

rhe values uf f ..

#include <math.h> Lnc Iude ,<sedio,.h>

void 'ta.bu.l.a't,e I(double (*f) (doub~le). II dopb~le fLrst,~ double Laat; ~ double Lno ) ;

int maic (v'oid)

{

'p'rintf ( I" Ent,er ini tial va l.ue r !'I')I; ':s-ca,nf ( II %:-If·~, &ini tia 1) ;

print~(~Enter final value: ~)i acarif (1~ %lfll , &final);

pr intf ( if Ent er incre'men t: II,. i acanf ( II' %1£ I~ ,r &:in'C'rement);

p~intf(~\n x cos(x)'

'I1I \n - .'_ - _ ... ..., _ - .. - - \n I'll ) ;

tabu.lateJcos, intt:ial, finalj incr,ementj.,;'

prin'tf , II \n x

Ij\n -,------

abulat,e(sin~ initial,

si,n (x) II

-- - - - - \n II) ; final, incremlent);

pr; tf (, U \n x an (x) IIIIII

'II \ n -- - - _ - - - - = ~ - - - \n III ) ;

t,ab'ulate ,(ta, '-II initial; final, inc:rementd;

}

ret:urn a ,r

}

void t,abulate (doub'l e ('*£'1 (doubled ~ doublBfirst, doub.l e last, dOluble Lncn)

{

double Xi

in~ i, Rum_intervals;

nun intervals =: ceil «(1~L6't -.;0 firl'st:) I ,inc'r) i f,o,r (i - a ,; i c;; num int'erVicils ,;: i++) (

x = first + i ' incr;

pri'utf" ( If %10 . 5f %10" 5f\n'~ If X, (- ,f) (x) ) ;

t.abu Lat.e Uti ~r tb: ced L unction wh! h also in emat.h .tre-. Wh n given 1_0 arsument x of dcubLe type, ceil returns the smallest integer tb,at 1.' _ reater th n or .. qual Ie I x..

Her ' . I W hal a .. e ion with tabul a tA!i "' c mi ht look like:

En er initial value: 0 En-te,l:' Lna I val u,e ~ ~ 5 Enter i.ncrement: ,,1

-

x

cos (x)

=-s...,. _

.IIII!I!!= ... -----

c.occno o ~ 1(H100 a .210000 0.30.000 a .aceno O~50000

1 00000 0.995100 0 .. 98'007 0,,95534 c ~ !~l21 016, o . B'7'7518

x

sin tx)

.....,..--- ~-

o . 00 o (lU)1 0 .. 10000 0 .. 20000 o ,.310000 0.40000 O~500DO

i(] ~ 0100'00 10 .. 09983 O.l9B67 0' .. 29552 o ~ 3,0942 0.47943

.X

I an (x)

0'.,00:000 0.100100 0.20000 0 .. 30000 0,.,400eo o .. 5100cro

O@OOOO(l 0' .. 1()OJ,3 0,. ,2,0271 0 .. 3093 ' 0 .. 42219' 0101541630

This _,' ric n I nd th . ne- t d·' I lU I r- 99~oinl< r-re] -, ures. B th re prinu _ ril _ I' f inte r _ t tc ad anced C prol. rarmn -r . m ' t reaoers - ill v: nl tn ,,k in the" I-e, . j ,n or

') ~n

int * restrict Pi

A pointer rhat's re '8 declar d usin res'trict is called a re 'It it:te'd poi'II.' ,F.. Th int ent h that if ,P point to au object that i lar - r mod ifie _ til ~ n th ~c t I bj ct il not

ac' ". ._ ed in any ~. ,I, .' other than throuzh Pili It, ternati \~, I ,(I I aClce.,. • I ..• b] I _ I

in. Iude having another pomter [0 -'. . ame obj ,lor ha ing P point 1- named

. ~,. bJe.. i 3' ing more til n ne wa " I_C -;jc,ct' ,Ifi D "aJL d " IllI-' i

LI.f, ~c k ' IL an xarnpl f ILh kind I < - beha ior lh I. ui ~t d jar

supp sed 10 di .. nrrnge, '< u·p', lh,~llp 3:11:_ q bI8-- -_ en declan d II'·

int * restrict p; int * ~e5trict q;

':_ i milar ituation v ould arise i . p w ._:. assign d tb, of, vari - ble or _' n

array element.i No mally it _, mld be J_'~a1 t c ,p~, p in -- Iq and then modify the imeg . r through '1::

q ~ p.,~

.'. ,

*q -= 0;

/* Causes undefined behav i or * I

Becaut e p ~ restricted POlDt r ho v' r th effect of executing tile ',- arement *Iq = 0; is unrk fined. By making p nd q point to .he " '. object, 'W'_ c_ used *'P and '*q 'to be aliases ..

externsloragll! class .,8.2 If it fi __ tricted pointer p i dec) I. d - a local variabk 'with, ur the extlern

~~OCk9''''Ut3 torage I, las: r'Bstrict appli _ .. nlv 'p hen the bk .k iu hicb P j., d elar d

i~ being e. '_ ,I 11 ed, 1"- ote i]lJ t rhe body ot a un lion is, a block.) re,E;Jtr co ct; can b

used with functi m parameters a. point r type, in which case it applies only when the function is x cutinz Wbn re'stric't is applied to ·8 point, r variable 'wilh

Ilsllooope:Jo. 't}.2 Hl.e ,- cope- howe ·ef- th res i tion k I.' '. _-'r lb - entire cecurion of tb_ progn rn,

The ,e ' I~ t rule, for usina restri,c,t rath - r omple ~ _" I __ ' .. 9 stu ~

dud JDI~'- II .1 ail . There 3LT ~ _ I ',-11 si tuati 0'- in which an alias let - ~. d from a

r tricted pointer is legal, For example a restrieted pointe p can be legaU,Y copied IJltO another restricted pointer ',mabIe q" provided that p is local to : __ fun _ tion and Iq i define -, in' idle a bloc -. III - , ted within Lb ~ function I bodv.

To Illustrate th '0-1- restrict. -, -, J. ok at ihe memepy md memmove <atring,h~rneader.23.B functions which belong It the <a.tri.ng'I h> header, memcpy bas.tbe followinu pr t ,I[ype in eg9:

void =memmove (void *al, const; vedd *92, size_t n) ;

vo.i d *memc-pl'y (void e's,trict sl" canst vod d * re,stri ct 82 I

s,ize t n';

~

~ · .. ] that itconies bvtes fr b~

memcpy I:: . imuar ~O strcpy exc pt at rt copies . yte uom one 0 Uect to.

anoth '- 'strc~pylcupies h a tIT from one 'trin.lo imo I __ other), s2 p' inr~ tethe

data to h.~ copied 81 p mts to I je destin __ tic D I f Ill" I· . d n is the numh -r

tIyt I to he opi d.The Ill, - f r,estrict-- ith b th sl . nd 52 in i,~- te that 1 Ie; urc , at tb c' p:y and the d,e~ lination sheuldn t overlap. (It d esn t gll.(J rantee th ,-c I thle'y don't O'V erlap, however, I

In contn , r, rlBstrict doe n'tapp If in th pm '-yp F rr memmove:

memmove d c: S the .~·am - IiUD,g a.Ii memcpy: Llt copi _ .. by,te. from me place ~o another, Tbe diff renee is lat memmove is guaranteed to WO'-~ e. en if the source anddestination verlap.Forexample .~ ... ould use tnemmove to hif he 1, ment of an an y b" on.. I position:

17.9 FlexibJe Arf~ ,Me,m'bers (C99~1 441

_-,no-r to IC19191~ there was no way tOI document the dilference between memcpy and merrmcve. The prototypes for 'the two functions were nearly identical:

vod.d *mem,cpyfv'o,id *61, conat; void *,62" s,i:ge_t nl; VO'LQ *memmove (void *sl" c.ot1stvoid *£12 ~ s,ize_t. nJ:

The use of restrict in the 'C991 er ion of memcpv's pr,ot,ol)pe lets Ule programmer know that 81 and 8,2 should poi.nL to objects that don' l overlap, or el se the function isn't guaranteed to WO,f " ~

Although using, restri,ct in rUDctionpro,totyp,es is useful documentation. that not the primary reason for its existence, res tr i,ct provides information '[0 the compiler that m,ay enable it to p educe [DOne ffieient cede-s-a process known

- eg ,eter storrase class; ""18.2 ,fit-, optl,j,lizafitJ,J" .. (The r1egi ste:,r storage class serves the' same P'UTpO' e.) Not ev,ery eompilcr attempts to optimize programs, however, and the ones.that do normally allow the programmer to disable optimizaticn. As a re: ult the C9'9 standard guarantee; that :r.·efstr,ict bas, noeffect en the behavior 0 a program that conformsto the standard; if all uses of .r@s,tri,at are removed from such ,8 program

,-

it should behave the same ..

MIOS'l programmers won't use re,stric't unless they're fine-mning a pro ... gram to achieve U1C' be sr pos -,ib~ P' irfurmanee. Still, :if' worth blOWin,g about r'estrictbecause it appears in the C' 9' prototypes for a number 'of standard Hbrary functions,

F'I'e- iV'!III'lb' le Arra- 'Y' IMe'

~;'A I .. , '--;,~ ,.' , . -_I, ' _I. 'I .

Every once in a while, we'll need to define ,8 structure tlla~' con tam' , an an ray of 11 unknown size. 'or example, 'we might want to ~ tore string, if I a form, that's differlent [rom the usual ene. No,rmaUy'l a tring is an array of characters. willl a IlUU character "larking tile' end. However, there are ad,\/anta.g: t:OI storing strings in other ways, 010', alternative is to store tbe length of the string along with the string s characters (but with no nuJ] character). TIlle length and the characters could be, stored in ,8 structure such as rhi - one:

B,t.ruct vstring { int Lenr

. ,t

char chars [N] ;' } ;

Here N is- a, macro that represents Ole maximum length of a tring, Using a fi tedlength array such as this is, undesirable, however because i fO'fC'!!S us) to limit the l .. ength of the string, plus it wastes emory (since mos t tring won't need all N characters in the array),

'C'p,rn,gvBJl1nlller. have traditionally s o~yed this problem b~ d _cl,aring lba l~'ngtb of char-s to be 1 (a dummy value) and [ben dynamically _ llocating each string:

44B Chapter 17 Advanced Uses ,of Pointers

struct v3tring , int len;

cha r chaxs [1] ;

} .

;I

,st:ru_;c't vstring ,st-..- = ma,lo,e(s'ze,gf'(struct vst.ring) + n - 1); str-'->len ;;:;. n;

W' 're "c 11_~ ing" by allocating more memorj than' hestrue ture is decla -eel to hav ~ (in this ell Ie - an extra n -] harac I_er 1- _" _ - th _ n u ,ine the mlc:ml ry

ti mal el m 'ut f the chars, arra _ Thi technic 1 , has b, com' 'I, I common aver

the years that it ha ~~ ;, na , : the "struct h~ ,-' .,'

The mu 'I hac ,', ., n 't limited [0 charact "r' arra: s: it has H. varlet}'" U - '., Over limeiL ha: b c me p pul " e ou ~h t 1 "b-: I upported b nlony ompilers, Som [including 0' chars ~ n y to h_,IC Z'_T length I '~i hi h male '

'th' ick ,3 li til 'J he :,' 9 ' t- d 'd 1-" sn't 'uaran~ -

• ' - - - I',

, hat the tru he, 10' zero-le nd ,W ravs.

In recognition of true, truct hack' U -I fulness, 91 h,21, ~ a feature [mown as the

fle~ .ible ,(I'~ °R__ member hat ,I· rVle~ th _Jlnl . purp,' I 'e,. . - ben the' 1 '. I~ m - rob . r nf a true ure i an array- its h n h fi,~· ~,' In1' . d:

struct vstring {

int len;'

char chars [] ; I *' flexible array member _, C9-g lonly * I } ;

.. he length of the chars isn't c et rmined until memory i all c " _d ror I

vstr'ing' tru WIre. nUTI ally using 3 call ·'·mallac:

at ruct, vat.r inq *s,tr .~ me.l.Loc (SiZB.lof (stTuct vBtring) 'n}; str"",>len = n;

10 thi .ample, str P ,"nt' I. vstr_ng tructur In which Lh, chaxs :

oceupie n haracters, The s i.zeof . p 'rat r ignore . the oha+s member wh 0 computing the size of the structure, A fle il b: array member i , unusual jn that -I rake np no pac within t stru ture.I

A r pe ~irJ rule pl' Or a tru ture that contaim a O .. ibl . r;r, memb -J~

Th n· j - II, • IT,· Y rnembe . must " PP: last in tb - . tru _ _ 1- and till ... tructure mUll

havr ar ]~U tone other member; . ',' in .. " structure ha c utaim ~ flexible arra member wit copy the oth er rn rnbers but not the flexible array itself,

A :,II"U _-lUI _ that coot U' - ,8 De Jbl array mem ' r j" n iftPfiQ,ml"lete I]pe,., An ineompleu typ , i I mi ~in, 'art I If the in I rmation need . til determine h,:" mu b m mory it requires .. Incomplete type hich are dis U sed further in on O~I the Q- A que lion a,' the end of LhL chapter and in Sa i m ~ 91 • .3 are nbjec ~. varirun re triction ~ In particular an incomplete 1ype I(and b - '0 I,', tructurethat contaim I la flexible array member can' am mber 0' W1l, tb _ ~ - tru _tUT' _f an element of :'J11 arrav. H ,'eI an array ma C' main pointer t str tur ~'- thit h - 'II:, fle ibl

array member: Programn ~L~ Pr ~ ect 7 · l the en hi '. h tet i built around

such an array,

'Q: WJlof does th -' NTJLL maern l}~p''fleseDt'?' I P'II IS]

A: NULL 31::tUaDy stands to I~l., When we us. 0 .in ,3 contei t where a pointer would b '

required compilers treat it as a null pointer instead I. the lnteger O. The NULL

macr . 'i ided D]' r :ly to he] p ,S old c nfusion, "he a signment

p = 0,;

. rould b - I .• _,i:_ ning th' . alu 10 ~ .1 a nu n,eri· riable r r ,,' igning a null I;t i t -I t . a

peintervarlable: we can't "ily t Jl whi ,h. ~n mra t~ the '_'S ignm o'

P' ~ 1It.1Tn·L'"

~ .!."iI U..LJ· ,

make' it clear hat pia pointer.

#define NULL (vod.d *) 0

. __ e of ea. ,.: II Ig 10 'to vo i d "'._

A.: ThL, trick, which is allowe by th C standard, enahk s compilers to spc inc nrect use 'Of the null pointer, For examplc. s m pose that 'A1'e tr to assizn NULL t : an integer vari able:

i == NULL;

varr1ab,l:e"I'en glhi arglJ me nt ltsts >'26,1

If NlTLL Is define as 0, this as ignment is perte tly Ie all. B'IJ,t if NULL, .1 defined ,., (volid *) 0, the compiler can warn UL that we")" ~_ igning a pointer to an int =. geJ~ . ~_tiab] ' ..

Defining NUL'L U' (void '*) 10 h:" I ecoud, mOF impor 'an - .. V~U1t g '~

Supp se hat we, c II . function i tb a - aris b I -1 ngth argum e - t 11 . and p . I NULL, as OD'r! of the arguments, If NULL j .. defined as a. the compiler '. ill incorrectly P' 1.'.'"

, zeru integer value. (In an ordinary funic-lion call NULL work I tine because he compiler knows from fil function 'ipro'l typ _ that it e p cts a solnter, Wilen a function h :. variable-length ar_ umen 11 t. 110. e .. er, the xnnpi] ~ ). cks hi" knowledge .. ) If NULILI is defined I. (void it) Ql th, compiler will pia, I i a null pointer;

To make matter CV,t:D mor .' nf ising, om heade r files de n NOLL to be

rOL (the long vier ion of O. This definition U I . th definition 0 . NOLL - .. 0 .. ~ .. a

holdover from '. earli r year " when pointers and integers W re c:ompa'ti ble, For m ' .. [ purp ses, thouzh, it really ld sn t rm tter how NULL is defined: jut think of it as a name for the null pointer.

Q':' Sin,. -,e 0 is u ed to represent 'tho _ null address with aD zero blts, righ 7'

A: Not neces saril . ~ach C'cc mpiler i . allowed to r PJ! __ 111 null point rs in a different wav " ~ d not an compilers use a ze ·,0 address, . or xam le, . on1 compiler .. , use a uonexistent m mory a.ddrl::-I' for the null pointer; that way" attempting tc memory through Ian III pointer dan be lei ~ . _I ct by the hardware,

How the null p . inter i' . rored in ide tile' cernputershouldn' t .' oneern 'U~·· that's a de 'tai ~ for c omp ill , r ,-: pert ' to worry ,abIOIUJl. _ 'he importan l thmg j n, that, when used 111 a point r conte t, 0 is I' n erted ,I tb ~ prope r in ernal "oml 'by th - cempile '9

IQ: Is itau 'ptabl_c_' to ~ se NULL " . I' nnlleharaete 1.'

A:: Definite ly not N11L.L, is a macro t_b' rl' resen I tb ouU,!O',int r. not th null (1Ih,Qr-

act. t: Using NULL ,.1. 8 Dl1H characn ~ 'will w rk.wim t, " _ om oilers I I' ut not with

. 11 I . lnee 1~'l.lm", defin NTILL ar (void *)1 0 ' .. In ~ln c' nit ling NU'LL . ' amy~

thmz .her than a pointer I an. I ad to 3. -Ie. eal f confusi n .. H ou wan nam .

. r the null, hara -t,[,; d ~ ~ ine the' foU . inc maiCl ::

#,define NUL ~ \0 ~

*QI:: WlI' n m,~' ~pliogram lermi~Qlates I r g~ t ' ,- hat do' this ,Rlean?

,- : Tbl', ne .. hich L

m _ iled . itn some '. ldr

, 'fl '-. - "Ill .

,t It message c'~ '.0. be ~' u . d by a

. ," e: ( n ~dU . ) "

,5:u~:,a II L ':b ~ f .1, ..

.L I,

l!'!Iip - -. ~

~ ..l!..~'

/* Pi ~euniui'tialized or null ~I

~~Q: . ,: 'P~OI' -ni - - -0, ~. that..' n~ ll"~' Im:te -a' . "gnm'DI ha o[.cur- ' ?

"": Themess g. d pends 01], tb fa t Ilu t, in the mall 3JJ1,d medium m mor- models I. ala, i, ' stor d in . I in ~ I, . egmen ~, with addresses .b ,ginn.ing at O. 'The compiler t ·av -. . I~ h Ic" at tb 'be '~nn]D . of the ,dataeg~mnt-a smaf block of memory thai I,. i' itialize . Ito 0 b n o:tb rwl e i~ n't used br rhe program." - len the program [! rminates, it cl ,ck~ 'to ee if any data in the 'ho \ 1- area i,·· nonzere.Jf.s . it must ha. .be n ,al ',ered through a bad pointer.

Q:: I'~I the' - WI ad ,an -, ',ge- to easting fhe return 1',3- '. ,oif mallo"c lor lb, -, otber me -0 -. ·U, 'ca:lin fune "ons? [p.416]

A: Not usuall . ~ 'e 'ling, the void *uinLer the t these fun rlon r·· to. i' I unnec .' ': ary I' inc' point r If typ', void * I ~,e u'(_ matically convert d t I an p in - t p

U on issignment, Ie habit of I-'~ I, ring tb, r ,-c urn ' . -.' 1 ue j z. ,-' 11 ]d,'" r from older

VI'-'_ ion . ".~ in "hi hth memon all mon run in returne ch,ar· Jue

'making the c st nece .. ary. that are desi I· .d .'."f!IJ moile '. ++code

m benefit from tbe -a t, ut har ~ bou th - onl rea': 0 It do it

In c~ '9', there's actually a smal! advantase to no' p rforrnin the cast, Suppo - that wev - J,'!J'go'[ n t ,I iJ1Clude lh· <,s dlib, .. h> h ader in our program " e 1 W all ma-ll OIC,~ the compi er will . , '. u me tba,l it return lyp' is int ,e the . ef ult return V,aiUL _0 any I' un tion . If ,- _' Ion't c t th eturn ralue 00; ma.lLoc. a C9 compiler will pr duce an err - r (or Btl ]. ~ Sl~ ,f! warni "U), since W 're tryin- to ass ign an integer value t a pointer variable, 'On the oth r hand, if e c . t 'h return 'V~ I ue 110 ,- , p oint er, the pmu,~am D_la_ compile but likely won It run properly, With 9 .. thj~ advanta ~ ,_lia-~p i1r_ i . 'O[':_ ettins to includ tb <: s,tdlib 'I! h,:> h_ ,31 ler will cau e an error when ma.l.l oc i· callec lee U'_ C9~' require ' lila, a function be declar d be ~or' it',. 10811 d.

Q:' ITh', IcalllollCl _unctinn ini ja'Uze a m,eI11-r bloc' ". b', I e:t'tinv :~'_I bi '. to z'e_ .'

Do~ - tb,'~ Jim, .. 'tbat dats ite _ ,_ in '_b ~ blOl:k b 'CIQ,m ,Ie~-_I·i· [p,,,,421]

.: snally, but not a1we(·,,<e ling an integer t, 2'Cl'.·. bit, al~a_ make the intes r

zero .. ~,etting, floatin '-p il'll number to Z '(10 bit: usuall' make the number zero but this isn t guarant d-i, :_I' _ .nds on how fin: fill: - "1 int num aers are "·1 red, 'The st ry i I the same for pointers: a pointer who e bi,' at ZIJI in t ne-e' ,: -_ a nun point r,

~-Q.'.'j1

.-;.', II

I I ee -_0' . 'ib I' ruetur tag ,to its ,I i Bn b ',_1 if ..... _ ''''-

.' ther? [P'i 4,2 .] A: Here ~ .. b, w w ~ 'd handle that . ituatiun:

rttb' 10'" --m ,aDo'w c·_ 13- : -UC_U 10 C It,I~" 18 pon 1- r

ha,_' " .:-~ m .mber that PIOi'D" "I I t ,Ie

struc't s1;

t* inc.omple'ce declaration of 81 * I

stru,ct 82 (

st,ruc:t sl ·p'1

} ,~

struct s1 {

} :

,.l1ocmplete t,PEIS ,..._ 19',3.

The first die lafllti n . J s 1 : .reates all incom plete structure type! j 111' ~Ie we ha en' t specified the members of sl .. '_ he :-, c nd declaration of 91 - completes' th - ,pc b ' die· r]l- ing the m mber of the structure. Incomplete d clarations of astructu typ are p rmiu 'd in C although their uses ar _ limiu d, Creating a point r to such a

-, p (a did when decl .. one p i ~ om . f th _- -u~e.,.

. II!

. ,

C ' 11in_1 mall,oo ."'Ib Ie rOD " _·0. --C.'.' . . It to I ~ :Uocate t, '.. mUI~'

me_ 1,0- to lit le m_mo _ ~ e IDS t~D - e a eommon -I",OE" Ikl there I . afer

- ~

ra to us -, aall,oc? [p~ 426]

A: Yes, there i ... Some programmers use '[be following Idiom when calling ma.Ll.oo to a~ I ocate rnem .,I[Y for a si ngle object:

Since si 'zeof ! *P'} is the size of the' ~ueC't to whicf 'Pi will point, this statement guarantees-that the COITe,c~ amount of memory wIll b allocated. A~ flrstglan tee.

"L.,,':: .... "d" 1,~ ....... If.''':: b II,~, lik I tl . .. . ~-: d , ..... 1.. . .:: ii-I. , ...... J f'

UJJl1 L 101m iooxs JUIS :y:: IrS ',f'.y l,ilIt P II unnuuahze maxmg me VaJUf' 0,1 '*p

undeflned. However, s Lzeof doesn't evaluate =p, it rnereb computes its size, SOl

d"'lEi ';j.,;.Ut .... -m work "" D\I.aWii if p :;, 'uru~Il11'·I~·')~·,,'-~I ... ~-d 0''1'" c'onil;i':Ii-~n. -Illil n-uJ] nointer

IJ..J.J~ J.Wu I, ''¥IF U. .<!'U ~,~.~. _' I~." .Il· . _' '_' l_~.~· .~ I.,t I ._Ib._QJJ.lI!"I.·~·1 Q_ I . _', r' '_ '_~.Ii!J

To allocate memory for Jan array with n elements, We cam use a slightly modi."';' ed vel" ion of the idiom:

Q:: Wh.'. bi,n-I. the g'sor't, function 1 impl' naDI1ed so:r't?' [p~, ·.0]

J\: The' name qs'ort. come .. from the Quicksort algorithm pubH hed by , ~ A,~ R,.

Hoare 'in 1'9162' i(and dl cussed in Section 9,'6)~ . ~ onlcally, (be C tandard do ~'.'n~[ require that qsozt; use the Quicksort algorithm, although many versions of qecrt do.

Q: lsn'i~ It _(.e,C'elS,3try to east q:Bor't,',I'1 Rrsi ar -um,e,nt to typ~ 'VQL,id '*" as in l.be'lo;lIG'wing lexamplle? [p~, ~~, -]j

«;Isort ((v,oid .) Lnvent.orv', num_parts, sizeof (stru,ct .part), comp,are _part B JI i

A:

No, ·A pointer f any type CM ' .. e converted 'La voi d '* automatically,

A:

] wan:t'to use qs,ort to sert an Brr,B. Jot" inte,ge -s,bllt I'm b,ovinl troubl,£ writ-

mil -- 0 " nom' ~·-In'arl""·. AD fun' - 'IA lon W"ha· "l"1 t he . ;fjiifi;f-A,'?I

b 1- - IL ,_, ~r'~ _.- U u 1 _ _ _~_L _ ~'l __ li _ • _' ' .' _._~~ L' [', "II-L~ ~ _' !iiI

Here's 1:1 version that works:

-o

"j.; ~

.. "

int ce,mp,are_int,s (conat;

{

}

return .* I( int *)'p ... * (int .. )1 q;

Bizarre, eh? The expression (Lnt; *J.p casts p to 'type int *~, "'0 "' I{int: *)p would be the in' eger thatp points 'to. A word of warning, though: Subtracting two integers ~nay. cause overflow" If the integers being sorted are completely arbitrary, if's safe-r to U81_:' if statements to compare '* (int .w) p with if I( i .. nt -If)1 q.

~l;Q:: I needed to sort an Br.tH,)?, lor strings ,'0 6gured d just' use Is,'t.r'lempl as, the eomparison func'tion", Wben I passed i,e 'til g's,ort,,_ bO'l',e~'e ~~, tble' comp,U,er I.,·e me' a . ,arI1iDR~ [ lriied to fix: the problem b._ e_m,beddi.nR IS tr"CDlp iu, ,. c1ol,mparj ... S,OD IUD,c·tion:

Exercises 453

int compaxe E;,trings. (ccnat

{, ~

}

A'

"

L t~

Now my prugtri,am, compiles" bul'gsort dues,D:''tseem to SUI"~ th,e-arJ'a,,YOI' Wh:at am I d,oingWTong?

First, you can't pass ,strcmp itself "]1 qso-rt~ since ,tq's!c1rt requires a cemparison function with two canst voi'd '* parameter. Your co,mpare=striogEl, function doesn' t 'work because it incorrectly ,8SSUlne <, that p andq are Sijtru11,S (char * pointers). In factp, andq point to array elements containing cllar * pointers. To fix compare_,strings, we 1] carl p and g - ,'! type char '* *' ~ then use the ... operator t~o remove one level of indirection:

canst. void *Q)

return strcmp(*(char **')p, * (char **)q);

] ,. Having to check the rerum value of mallo~C! (01" any other me'mol){ a.ll~gclti!01ilr function) each time we ca..n it can be ani annuyance, Wri lea runcjon named my_mallolc that serves a's, a "wrapper for rnaLl.oc. Wbenwe ,c31'1 m'Y'_m,all'oc anu ask ~L te a11o~alte' c by~te's! it in tum c.oJ} , ma LLoc, tests to make sure Ulal mal.lol1t=, doesn't return ,0 ,nun pojn'ter. aq,d thcn returns thepointer fromma 11 oc, Havemy ...... ma..ll!oc' print DD error message and ~,ef.1Diont-e the program if mall 0 C returns a null ~p'omleri

18 2. Write ~1 function named dup 1 i ca t e that uses dynl3Tl1 ic storageallocalion to create 11 C'['Jrpy of a string, For 'f3'Xl3111ple" the call

P' ,~ dup.Lf.cat.e (str)! :

would. al ~O.c,8~C space fur a string of ~be same J!engtl1 as s t~. leap)! the conteo.ts of B tr into the new string, and return a pointer to l't. Have dup,lic.ate, return a nuH pointer if the 'mlemory allocation fails.

• I ' ~ j,,; 1 1 )

a nt; 'itcr!eatl®_array \ a.nt, n, ~nt l.n~ t1.a-_va rue ;

The function should re[UD1 apointer 'to! it dynanlica]ly allocared Lnt, array withn members, each of which ~r5i initialized '~O ini,tia,l va L ue. The' return value should, be 'N1JLLi'f the arra y can ~t be allocated,

4. Suppose ~hat the fellowing declarations ar-e in leffe~I[: 'struct paint { int XI' Y;, };

at; ru,ct r'E!ct ,ang 1 e { B tru.C t P,OiD,'t up,per_l e£ t J' lOiw'er_r.igh t ,; };' struct r~ctangle *p;

·1 I" ume thm ::,' -'r;ln. p Ito p iDE to ,I, rectii;'gle struc lITe' ~ 110 .. '1: 1ll1'P' r I f[ em r i

~O,' 25 ~nd ",b se lower right I . " r 1 ,at (20, 1 ),,' rite I I ,eLi _ f tatement 'that an .

c uch a "b1J, u.ue and liniti,8Hze it ~. ' indicat ' ' ,

,51. . uppos e that f and p aT' d

stru'c't {

und.on {

char a , b;: int C;

} d;

it1't e [5] ;'

}- f ~ * Pi ;;:; &f;

Whi 'h ,f the followia (a) p- >b -- ~, II 1

--) p"'" >e [3 J = 10;

1(1 ' (-*'p)l" d . a. ~ ~ 'It ! ;

(dl' p- >d- >G iiii: '~,Ol;'

6, ,'" "odi:fy the de:l,ete_from_list uncuou sorhai Inl U_./, only onepointer I ariable in'~e[1_ 0' tw I (cur ,m.dpr'ev) ..

7 ~ The .' llowing l p i' : 'uppo',ed '~O delete aU D . fr m a linked list land releas _ I • h - mem ry

thar they cup' t .' nfurtunatel th to i inion ct. Bxplaln what , W[I . with i and

,how how to fix the bU,B ..

flo,r (p ~ fir-s t; P l'~ NULL; p. ~ p - '~nlext ) free {pl)1 ;

8

. -.\~

,~cli,on 15,~ -~ de eri _" 'i'i 1 \' stack" c, 'l1-1 1,[ _.ro~ td' un ti . r It I ring mtege in a .,tlLck~ ]0 iha section, the . tack 'WI: implement d as 'aft ocr-ay, M, djfy' s t ack • C' I '0 tbat it i - _- S· [led a a Iinked Ii l _, place til Icanten t s ' nd top c'ri bl . b~ I jDg~ variabJe' that points In lh. ',Inr~l ode in the ll: r r( the I~ top' I I Lh· lac ." ) .. Wri~e Ul fun, lion "I in, st:.aek;; CI' that lh - u _ his P' inter, Rem e th iSI_full _-w1cd n, lnstead h iJ1~ p,ush rerum ,either' tru,e (if memory was available ~o cres te a, IDod _ r £ - 1 !i,e (if Otll)l.

True or fal .. '; II x i ~ a stru zure and a is IPI member oJ that strucmre, lh.' n, '&x} .... :>a i'l the

Iii. - I I' X if a, In ti - our'n

9.

~O~ lb. print_part Iu etion of e ti n I -:. thal 'i s oaram . r is, pointer In n

part structure, U.Cr the .... > operator in your an WI f.

II ] • W rite the ollowing function:

int c()unt_ocr!llr'r.en.ce'~ (8 zuct; node ·'l~at,~ inrt n)l;

The 1 i at param ter pain, l n ,d IL_ , the fun ti n should return th number f tim, I I. , It t n a,ppe. i.) in this U.: t, A ss 1lI me that the node :. rruenrre i th - one' defined In ". ection J 7.7.

I, _ '. ;; - rile the ~CI llowing runetl n:

struct node *find l,ast I(stru'c:t node *lis _, int n) i

'The li,st plaramete.r points t ,8 Un~ d lit Th - fun_lion .h_uld return ~ ... inl :r tu the Ia I node that contains n; it 111 uld 11 tum NULL if n doesn't appear in the Lilt. As'sum· ~Jhal the node strueture i I' he on 'd,~finl_'d. in _- it! tin 17~·''_ ..

f ~, The follo . 1. ng fun. tion 1· uppo ed to in I, rt a ne ned in~D d proper pl· ce in list, returning a pointer to die first n d in tb modified U t. Unfortun Jel'y Ihe function

doesn't wolk correctly in a.U cases, ' xplain what's wrong with it 3Dd show how' ~o fix it Assume thatthe node structure is the one defined in Sec tion l7.5.

at ruct. node *inse,rt Lnt,o o r'de,r ed- list (s'truct, node "list,~

- ~ ~-

8't.,~uct node *new~no,de)

st:,ru,et ,[l,.(lt:!ile- cur ~ 1 is t I~ *I:lre:v: = NULL;' 'while ( cur-- ;.:vaLue <~ new_node~ ~~alue) { prev - cur;

cur = cur~>next;

J

pxev- vnext :; new node,

n€!'w_-, na"d"e ""' ~n_'lext_'- - cur·

~ , .c_.'_ ""

return li,at. ~

}

Section 117,.,6

14. Modify the de:letia~from~l.1st function (Section 17.5) so tit at its, lits,l parameter bas type s:truc''t node .*1It (a pointer to a pointer to the fir, II node in :1, lisU and i.t ' return type is void. d~.@1'E!te_frD:m_li,8,'tmu,sl modify its fin;[ argument tD poim to the list aJ1tE;r the desired node bas, been deleted.

1.5". Shewthe eutput of the roUowmg program and explain what f~ does, linclude <stdio",h>

int fll( int (*f) '(in't JI ) ; Lnt :f2"lint i) ;'

im: main ('v,old.)

{

printf ( lIAn:s'war :%'d\n~" r f1 ('f2)1 ~ l re'tUTn (] ~

)

int fl ,( int I{ ~ f')1 ,( Lnt 11 )

{

while (( *£) (n) ) rB-turn D;

n++"'

. ,

}

i,nt £,2 (int i)

(

return i ,tr i + i- 12;

}

l'6" WF.]t~ the following function, The call aum (,g, i ... , jl' should retum 9 (i 1 + . ~'I! + g( 'j , . i nt S1J;m { .int ( * 'f)1 (~in't) ~ int 1St ar1; ~ J1n't end 1 I

l7'. Let a be am ,array of 100 integers, 'Wri,lte a [!a1J 101' qeoZ"'t tItlrlct sorts only the las: 50 clements in a, f'!'tou don't need to \\Y]ire [he eomparison funetion),

18. Modify the ,C!llomplarr:;:',_par t 61 function sDdJ',a~ parts are :!ii,urted wlltb tbeir numbers i.n de'scel!di"~l1 order,

I'gl. Write ~ fUlled,on that, wben given at string las its argument, searches the foUowingWT3Y of struetu res . ~Ol' a, matching command name, l\be;o ICWh the fu I' cU on associated w ith {b~tr1aau~.

stru'ct {

char' = cmd name 1

v.oi.d ( c.mdj)ointer-)' (vDid,) ; } f i1 e cmd [ ] 0:::

{ ,{ iill n1ew ~II ~'

{ 1III open' "

{ ID o l.oae II I {uc,lose all II I { iii s ave u ,

{ IIII aave as ffi I

{ ~II aave all rl , { I print 11'1

{"exit u I

} ~I

I

new~cmd} , loplen~cmd} , close cmd] , cLoae all cmd] , save _ cmd] ~ eave_as_cm,d} t save_all_leTnd] f priIlt:~cPld} , exit_cmd}

I 1 ~ Iodify !h ' i.nverrtozy ~ c program IOf Section l6 . .3 ,0 that (be inventory array i allo-

cared d.ynamically and latet reallocated when h fills up. U " ma,lloc: iD'iuaHy La alloeat en ugb space r r an array r f 10 part .. tructure . hen the arra has lID more mom fB.r neVII" part ", U - r,e,alloc to d uble i size, Repe 'l 'lb, d ubHni'ltpl leach time the aIT,a' becomes fulL

2,. . oldi1~/ the inventory., c program of I - 'lion 16.3 ' 0 Lhla:~ the p Iprint) ornmand calls qsozt; to ort tile' invent o,ry ~8:Y b f re it print' the part I,,,

3. Modify the inventory2 ~crogr.am of.' ection 17~S. b' adding an ell' I e) cemmana that allow' the u.er to remov 0, part (rom be. I[ ba e,

4. Modify th ' jus t ify program I 'f Section ~'~. ,'I by re ritin the liFle i c file 5:0 that ir stores the current Ilne in a linked list, "1 eh 'node in [be list ;wlll store a 'single word. The 1 i.ne array 'will be replaced b_ ,_. variable th'd points to he node containing the t1rst word .. This variable wi U ., tore a null point- r whc;. J the line i empt ._

5. 'rite a program 'thai' art a series I I Wi f.'· lent, red b~ the De r:

Enter w,o,r-d: £00 B~nt'er word:: bar ~ntler wD,rd: baz E,nt.er word:. quux B:nter word:

I_n sorted or'der: bar 'baz f oo quux

ume that each word is no more than 20' characters ~ang. ,- top reading ben the u er en ers ;an empt ~ord, i.e ... presses - Ol -r ilb,· ut entering a word). ' ... tc Ie each I ,ord in a dynamicall _ all . ated . tri ng. uing· ,an array If .', in~e'rs t keep 11.1", C - of he uing ,~, _ in [h~ rlemind2' . C program (S· -'0· n ) 7.2. AIl_ r all ' -" Ids ha. e ,I~J"O read ort lb array (1.11- in J any sorting technique) an then u e a Ioop t print Ill' w 'ro tn -rted ord r. Him: Use the rea,d lin,s fUnction to read ealch word. ill in r'em.ind2 ~,C'.

16~ M dify Pn gramrning Proj ct 5 ',0 'that' uses qs.ort to I, Oft the mnuy of p lnters,

7E C99 Modify the remind2 - 0 program of Section ]7.~ 0 that each element 'f the

reminder!1 array is a P 'inter '0 a vstringl11J£tlu~e see c e: ,-~ ,n ~ 7. I' rather than 18 pointer tiel an ordinary string"