ebook img

Understanding Pointers in C PDF

255 Pages·2003·64.19 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Understanding Pointers in C

iElr rrE lrrytsa IEEffi {r, G6 E- @ G' E -Y,,^ t f"ttti l-.:. .I'PB PUBLICATIONS Table of Contents Aclotowledgments 2. Pointers atrd Arrryr ... Jntrcduc|ion Io Second Edhiot IDtroductio[ To Poitrters,,,,,....,..;...............,.......-.......1 The & and , Operctors, 2 Poifier Explessions, 4 The Jargon of Pointers, 9 char, int andfloat Poihters, 9 Passing Addrcsses to Functiohs, 12 Fuictions Retuming Pointers, 15 Solyed Problems, 17 Exercise, 30 Pointers and Stings, 142 The const Qualifier, 143 Retumirrg eonst Yaluef, 146 Two Dirtensional A|ray ofCharacters, 147 Array ofPoi\rers to Strings, 149 Lirnitario4 ofArray ofPointers to Strings, I 52 Solved Problems, 154 F,xerclse. 184. ttv,' 4. PolnterrandStructures ......,..........------------.,.........189 An Array of gructures, 191 Mole about Structures, 192 Structure Poi ters, I94 Offsers ofstructufe Elemehts, 196 Linked Lists, 200 Stacl$ and Queuet, 220 Doubly Lhked Lisk, 2ii Solved Prcblens, 243 Etercise,270 5. Pohters rlrd Dats Structurcs ...,......,.,..........,,,,.....,,,...,....279 Mergirrg dLinked Lists, 280 t- llhat are Arrays, 38 Passing Atay Elernents to a Function. Poihters and Atays, 43 Pqssing a4 E ttirc Affoy to a Function, TheRealThing,5l Morc Thqn One Di ension, 52 Poinlers arrd Tfuo Dimetsional Arrays, Poi tetto sn Atay, 58 Pdssing 2-D Arroy to a Function, 59 Three Dimensiondl Arrays, 62 Passing 3-D Array to a Functiok, 66 Retuming Aftayfrorn Fuictiot , 69 Relumifig 3-D Aftay from a Function, Array of Poi ters, 82 Dyuhtic Memory Allocation, 84 Solved Problems, 87 Erercise, 130 Pointers and Stiitrgs ,.....................133 Wat are Slrings, 1j3 * Li ked Lists and Polynonials, 285 Sotting a Lin*ed List, 297 Circalar Linhed List, 323 Trees, 326 Binary Tre*, j28 41 50 3. Stqhdard Library String Funcrions, I38 vt Traversal d a Binary Tree, 33 1 Deletionlrom a Binary Tree, 336 Threaded Binary Tree, 344 Graphs,356 Solved Problems, i69 Exercise. 389 6. PointersMisceIlrtry..,,,.....................................................391 File Poi rets, 391 Pointers to Functions, 394 typedef with Furrction Potuters, 397 srgc and srgv - Arguments to mairt( ), 398 Poin ers afid Ydriable Nurnber of Argunen s' 399 rcor,lat and huge Poinlers, 40i Which Poi en to Use?, 408 Physicol ,4ddrcss to Segne :qsel 4 I I The Darcing Dolls, 412 Caps Locked!, 413 How Much Memory Do You Have?, 415 Exercise,4l7 7. Appllcrdorr of Pohters '..,....--........................................423 Exploting the Dith 423 Dictioiary, 434 Manoging Database, 439 The Keybod Queue, 459 InJix to Postfa, 462 Evaluation of Postfa Exprcssion, 467 Locatw Duplicote Filelanes, 469 Eoshing 474 i Function Calls and Stqck. 480 Solved Probtens, V85 I tnrex | 493 Preface to Third Edition In all walks of life anythiDg can be done better the next lime around. I realised this more emphatically when I completed lhe third edition oftlds book. Ihus, Ore so-cJlled ,perfect' c'hapters of the second edition had to be redone for more clarity and simplicity. For quite some time now I have beeo getting requests fiom readers that the chapter on .pointers and Oata Structures, be made more elaborate and exhaustivg. I have completely overhaule.d this chapter. Now it also includes binary treis ani graphs, While reading the fust draft ofthis edition I felt that something is missin-gin this book. It was only when I was ttuougtr *ittr rtr! final draft I.realisgd that the missing link (poinrer) wa-s a chapter on applications of pointers in real-world programming. After all, no amount of theory is useful unless you cun poi it into practice. So the final draft became semifinai since I decided to add this chapter to the book. And now I am presenting you the edition which I feel is complete in all respects, lili I "- pmying tlat I won't be required to wrire aflother editiol of this book, Any author would testiS/ that writing a new edition is always more palD in the neck than writing a fresh title. tt Poihten ca be tuade to work ifyou frddle ,a,ith them lo g e ough. Ifyou Jiddle with anything long enough you wilt uttimately fiess it An Introtuctionto Qointrs f f Tbich featue of C do beginners find most difficulr to VV understand? The answer is easy: pointers. Other v V languages have pointeE but few use tbem so freely, with such abandon, as C does. Aod why rct? Ir is C,s clever use of pointeN that mak€s it the excellent language it is. The difficulty begiDners have with pointers has much to do with C's pointe, terminology than lhe actual concept. For instance. when a C progmmmer says that a cedain variable is a . pointer.., what does that mean? It is hard to s€€ how a variable can poinr to something, or in a certain direction. 2 Understanding Pointers In C Chapter 1: An Introduction to Pointers 3 It is difficult to get a grip on poioters just by listening to programmer's jargon, In our discussion of C pointers, therefore, we will try to avoid this difliculty by explaining them in terms of simple programming concepts. The fi$t thing vi,e want to do is e\plain the rationale ofC's pointer notalion. We oan print this address through 1Le /- Program 1 */ main0 { inti=3; following program: The& and * Operators Consider the declamtion, This declaration tells the C oompiler to: (a) Reserve space in memory to hold the integer value. (b) Associate the name i with this memory location. (c) Srore the value I ar this location. We may rcpresent i's looation irl the memory by the following memory map: i-__} El--* 6485+ Location Dnme I-ocation no. (Ad&ess) Figure l.l We see that the computer has selected memory Iocation 6485 as the place to store the value 3. This location number 6485 is not a number to be relied upon, because some other time drc computer ult r\, may ohoose a different location for storing th€ value 3. impofiant point is, l's address in memory is a number. printf ( "\nAddress of i= %u^, prlntf('hvalue of i = %u", i) ) l'he output ofthe above program would be: Addrcss ot i= 6485 Value of i= 3 &i) ; inti=3; l,ook at the fi$t printf( ) statement carefully. The .&, opeBtor [sod in this statement is C's 'address of operator. The expression &i retums the address ofthe vagi4llglwhich in this case happens lo be 6485 pointer operator avaikble in C is '*'. called 'value at erator. It retums the vaiiE stored at a particdlalEddfess. also called an 'indirection' at address' operator is l,hlene carefully the output olthe following programj /' Program 2 '/ nrain0 I inti=3; printf ( "\nAddress of i = %u', &i) ; %d-, i) ; %d",.(&i)); printf ( \nvalue ofr = other ess o e'value orator. printi ("\nvalue of i= ) Ttre IJnderstanding Poinlers In C Chapter I : An Introduction to pointers 4 5 The output ofthe above prog€m would be: Addressoli=6485 Valueofi=3 Value oli = 3 Note that pdnting the value of *( &i ) is ofi. As you can see, i,s value is 3 andj,s value is i,s address. "l:1^1"]! ". :an'r use j jn a program wilhout dectaring it. And 8rn.e j rs a \arjable. which conlains lhe addre., of i, it is-aeilurea- 0r. lnl 'j ; 'lltis declaralion tells the compiler that I will be used lo store the rddress ofan integer value _ in o*re. *Jro.; poino ,o _ iri"g;; Ilow do wejustify tlie usage of * in the declaiation, lnt'j; 1;d ,t g:-Py the meaning of +. It stands for ,value at address,, I hus,.irt *J would mean, the value at the addre* ""","rn"ji, ij, same as printing the value Pointer Expressions Let us now see what are pointers and how they can be used in various expresJions. We hav9 seen in the previous section that the expression &i retums the address ofi. If we so desire, thig address can be collected in a variable by saying, But rcmembcr that J is not an ordinary variable like any other int€ger variable. lt is a variable, which contains the address of llcre is a program that dcmonshates the relationships we have t ccn discussing. another variable (t in this case) Since J is a variable the compiler must provide it space in mernory' Once again, the following mcmory map would illusts?te the contents of I and J. E'.-l 6485 3276 Figure 1.2 j=&i; I Program 3./ maino ( inl i= 3; int 'j ; j=&i; pdntt ( '\nAddE$ of i = %u', di ) : printf ('\nAddEss of i = %u'. i ) : Printf ( '\nAddress ofj = o/ou', ai) ; pdntt("\nvalueotj=%d'. i ) :' pdntf ( 'hvatue of i = %d", i i : pdntf ( 'hvalue of j = o/od,. .{ &i ) I . Printf ('\nvalueof i = %d' l) "' 6 (Jnderstanding Pointers In C Chapter 1 : An Introdaction to pointers 7 The output ofthc above program would be: AddEssoli=6485 Addressofi=6485 AddEssofl=3276 Value ofl = 6485 Valu6 ofl = 3 Valueoli=3 Valu6 of i= 3 Wo* thrcugh thc above program caretulln taking hclp of the memory locations of t and J shom ea isr. This program summarires everything we have discusscd so far. If you don't understand thc'program's output, or the meoning of ihe oxpregsions &1, &J, rl ard *( &l ), re'read the last few pages. Evcidring wc say about poilters ftom hcr€ onwards will dcpcNd on your understanding ofthcse exprcssions thoroughly. Look at the following dcctarations, lnt'alpha; ohar 'ch ; lloat 's : Hcrc, rlphr, ch and I ale declarcd as pointer variablel, i.c' variableicapable of holding addtesses. RfiIember that, addrgsses (location nos,) ar€ always going to be whole oumbe!$, thorcfore pointers ahvays contain whole numbers. Now we call put these two iacts togethir and say-poiotels are variables that contain since addrcsses ai;;lwaysE;G;mBEiies !way would always co!!Bi! concept of pointer caD be further extended. pointer we know is a vadable, which contairc address of another variaUte, Niw thii variable itself could be another pointer. Thus, we now have a pointer., whicb.contains another pointer.s address. The following example should make this point clear. f Prcgram 4'l maino { iiqt i= 3; int'j: lnt nt; j= &; k=&j; pinf ('bAddr€ssof I = %u., & ) ; Ptinu ( trAddcss oti= oi6u', j ): pdntf ( lnAddEss of i = %u., ik ) : Pdntf ( '\nAddrsss ofj = %u', &j i ; pdnf ( lnAddrEss ofj= %u', k ): prinf ( tAddrBss ofl( = %u', &k ) ; prinf ( lnhvdus ofj = %u', j); pdnf ( Walus of k r %u', k ); printf ( '\nvalue oti = %d', t)j pdntf( lnvaluo ofi =/od',.(&j))j pdnf (hvalue of i = %d", J ); pdnf( lnvalueofi = %d',,* ); The declaration llgat *Ejqes not mean lhat s is going [o cooBln a fl oati-ng-point valqq. @ --aterisi-oIa'hoating-point value. Similarly, char *ch means that ch is going to oontiin the address of a char value. Or irr other words, the value at ad&ess stored in ch is going to be a ch'r' The The output ofthe above program would be: Addressoti=6485 Addre6sori=6485 AddEssofi=6485 AddEssofj=3276' 8 Understanding Pointers In C Address ofj= 3276 Addressolk=7234 Value ofj= 6485 Valueofk=3276 Valueoli=3 Valueofi=3 Value of i= 3 Valu6ofi=3 The following memory tDop would help you ir tmcing out how the prcgram prints dle above outpul. Figurc 1.3 Obs€rvc how the variables l, J and k have been declarcd, inti; lnl -l i int -k i this, one mrely requires to just in case... extend the definition of a Pointer' But H€re, I is an ordinary ldt, I is a pointer to ar lnt, whsreas k is a poiflrer to a pointer. ln pdnciple, there could bG a pointer to a ;ointer to a pointer, or a pointer to a pointer to a pointer to a pointer. There is no limit on how far can we go on extending this a€finition. Possibly, titl the point we can csrFehetrd it' And that point of oomprehensiotr is usually a pointe, to a pointer. Beyotd char, int zad.Jlod, Pointers Considei the followiog program: f

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.