Professional Documents
Culture Documents
Elr
rr
lrE
rytsa
IE
E
ffi
{r,
G6
E-
@
G'
E
Y,,^
t- f"ttti
l-.:.
.I'PB PUBLICATIONS
Table of Contents Pointers and Stings, 142
The const Qualifier, 143
Aclotowledgments Retumirrg eonst Yaluef, 146
Jntrcduc|ion Io Second Edhiot Two Dirtensional A|ray ofCharacters, 147
Array ofPoi\rers to Strings, 149
t- IDtroductio[ To Poitrters,,,,,....,..;...............,.......-.......1 Lirnitario4 ofArray ofPointers to Strings, I 52
The & and , Operctors, 2 Solved Problems, 154
Poifier Explessions, 4 F,xerclse. 184. t
The Jargon of Pointers, 9 tv,'
4. PolnterrandStructures ......,..........------------.,.........189
char, int andfloat Poihters, 9
Passing Addrcsses to Functiohs, 12 An Array of gructures, 191
Fuictions Retuming Pointers, 15 Mole about Structures, 192
Solyed Problems, 17 Structure Poi ters, I94
Exercise, 30 Offsers ofstructufe Elemehts, 196
Linked Lists, 200
2. Pointers atrd Arrryr ... Stacl$ and Queuet, 220
llhat are Arrays, 38 Doubly Lhked Lisk, 2ii
Passing Atay Elernents to a Function. 41 Solved Prcblens, 243
Poihters and Atays, 43 Etercise,270
Pqssing a4 E ttirc Affoy to a Function, 50
TheRealThing,5l 5. Pohters rlrd Dats Structurcs ...,......,.,..........,,,,.....,,,...,....279
Morc Thqn One Di ension, 52 Mergirrg dLinked Lists, 280
Poinlers arrd Tfuo Dimetsional Arrays, * Li ked Lists and Polynonials, 285
Poi tetto sn Atay, 58 Sotting a Lin*ed List, 297
Pdssing 2-D Arroy to a Function, 59 Circalar Linhed List, 323
Three Dimensiondl Arrays, 62 Trees, 326
Passing 3-D Array to a Functiok, 66 Binary Tre*, j28
Retuming Aftayfrorn Fuictiot , 69 Traversal d a Binary Tree, 33 1
Relumifig 3-D Aftay from a Function, Deletionlrom Binary Tree, 336
a
Array of Poi ters, 82 Threaded Binary Tree, 344
Dyuhtic Memory Allocation, 84 Graphs,356
Solved Problems, 87 Solved Problems, i69
Erercise, 130 Exercise. 389
vt
typedef with Furrction Potuters, 397 Preface to Third Edition
srgc and srgv - Arguments to mairt( ),398
Poin ers afid Ydriable Nurnber of Argunen s' 399 In all walks of life anythiDg can be done better the next lime
rcor,lat and huge Poinlers, 40i around. I realised this more emphatically when I completed lhe
Which Poi en to Use?, 408 third edition oftlds book. Ihus, Ore so-cJlled ,perfect' c'hapters of
Physicol ,4ddrcss to Segne :qsel 4I I the second edition had to be redone for more clarity and simplicity.
The Darcing Dolls, 412
Caps Locked!, 413 For quite some time now I have beeo getting requests fiom
How Much Memory Do You Have?, 415 readers that the chapter on .pointers and Oata Structures,
be
Exercise,4l7 made more elaborate and exhaustivg. I have completely
overhaule.d this chapter. Now it also includes binary treis ani
7. Appllcrdorr of Pohters '..,....--........................................423 graphs,
Exploting the Dith 423
Dictioiary, 434
While reading the fust draft ofthis edition I felt that something
Manoging Database, 439
is missin-gin this book. It was only when I was ttuougtr *ittr
The Keybod Queue, 459 rtr!
InJix to Postfa, 462 final draft I.realisgd that the missing link (poinrer) wa-s a chapter
Evaluation of Postfa Exprcssion, 467 on applications of pointers in real-world programming. After
Locatw Duplicote Filelanes, 469 all, no amount of theory is useful unless you cun poi it into
Eoshing 474 i
practice. So the final draft became semifinai since
I decided to
Function Calls and Stqck. 480 add this chapter to the book. And now I am presenting you the
Solved Probtens, V85 edition which I feel is complete in all respects, lili I
tnrex
I
| 493
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
It is difficult to get a grip on poioters just by listening to We oan print this address through 1Le following program:
programmer's jargon, In our discussion of C pointers, therefore,
we will try to avoid this difliculty by explaining them in terms of /- Program 1 */
simple programming concepts. The fi$t thing vi,e want to do is main0
e\plain the rationale ofC's pointer notalion. {
inti=3;
The& and * Operators printf ( "\nAddress of i= %u^, &i) ;
prlntf('hvalue of i = %u", i)
Consider the declamtion, )
El--*
6485+ I-ocation no. (Ad&ess)
orator.
Let us now see what are pointers and how they can be used in lnt'j;
various expresJions. We hav9 seen in the previous section that the
expression &i retums the address ofi. If we so desire, thig address
1;d
,t g:-Py
the meaning of +.
It stands for ,value at address,,
can be collected in a variable by saying, *J
I hus,.irt would mean, the value at the
addre*
""","rn"ji, ij,
j=&i;
llcre is a program that dcmonshates the relationships
we have
But rcmembcr that J is not an ordinary variable like any other t ccn discussing.
int€ger variable. lt is a variable, which contains the address of
another variable (t in this case) I Program 3./
maino
it space in mernory'
Since J is a variable the compiler must provide (
Once again, the following mcmory map would illusts?te the inl i= 3;
contents of I and J. int 'j ;
j=&i;
pdntt ( '\nAddE$ of i %u',
= di ) :
printf ('\nAddEss of i %u'.
= i ):
E'.-l Printf ( '\nAddress ofj =
pdntt("\nvalueotj=%d'.
o/ou',
i)
ai) ;
:'
6485 3276 pdntf ( 'hvatue of i %d",
= i
i:
pdntf ( 'hvalue of j o/od,. .{ &i ) I .
l) "'
=
Printf ('\nvalueof i = %d'
Figure 1.2
6 (Jnderstanding Pointers In C Chapter 1 : An Introdaction to pointers 7
The output ofthc above program would be: concept of pointer caD be further extended. pointer we
know is a
vadable, which contairc address of another variaUte, Niw
thii
AddEssoli=6485 variable itself could be another pointer. Thus, we now have
a
Addressofi=6485 pointer., whicb.contains another pointer.s address.
The following
AddEssofl=3276 example should make this point clear.
Value ofl = 6485
Valu6 ofl = 3 f Prcgram 4'l
Valueoli=3 maino
Valu6 of i= 3 {
iiqt i= 3;
Wo* thrcugh thc above program caretulln taking hclp of the int'j:
t
memory locations of and J shom ea isr. This program lnt
nt;
summarires everything we have discusscd so far. If you don't
understand thc'program's output, or the meoning of ihe &;
j=
oxpregsions &1, &J, rl ard
*( &l ), re'read the last few pages. k=&j;
Evcidring wc say about poilters ftom hcr€ onwards will dcpcNd pinf ('bAddr€ssof I = %u., & ) ;
on your understanding ofthcse exprcssions thoroughly.
Ptinu ( trAddcss oti= oi6u', j ):
pdntf ( lnAddEss of i %u., ik ) :
Look at the following dcctarations, =
Pdntf ( '\nAddrsss ofj = %u', &j i ;
pdnf ( lnAddrEss ofj= %u', k ):
lnt'alpha; prinf ( tAddrBss ofl( = %u', &k
ohar 'ch ;
);
lloat 's : prinf ( lnhvdus ofj %u', j);
=
pdnf ( Walus of k r %u', k );
Hcrc, rlphr, ch I
and ale declarcd as pointer variablel, i.c' printf ( '\nvalue oti %d', t)j
=
variableicapable of holding addtesses. RfiIember that, addrgsses pdntf( lnvaluo ofi
(location nos,) ar€ always going to be whole oumbe!$, thorcfore =/od',.(&j))j
pointers ahvays contain whole numbers. Now we call put these two
i
pdnf (hvalue of = %d", J );
pdnf( lnvalueofi = %d',,* );
iacts togethir and say-poiotels are variables that contain
since addrcsses ai;;lwaysE;G;mBEiies
!way
would always co!!Bi! The output ofthe above program would be:
The declaration llgat *Ejqes not mean lhat s is going [o cooBln a Addressoti=6485
fl oati-ng-point valqq. @ Addre6sori=6485
value. Similarly, char *ch means that AddEssofi=6485
--aterisi-oIa'hoating-point
ch is going to oontiin the address of a char value. Or irr other AddEssofj=3276'
words, the value at ad&ess stored in ch is going to be a ch'r' The
8 Understanding Pointers In C
Address ofj= 3276 this, one mrely requires to extend the definition of a Pointer' But
Addressolk=7234 just in case...
float a,'aa;
t/
c= 'A I ascii value of A gets stored in c
i=54;
a= 3.14; EI
1004
lE;;l:;7l
2009 7006 7007 7008 7009
3.14
ii= &i i
aar&ai
pdntf \Address contained in cc = %u", cc ) i ii
plintf '\nAddr€ss conbined in ii = %u", ii ) ;
pdntt '\nAddl8ss ontained in aa = %u', aa ) i
@ 1962
m8l
7602
p ntf "ivalue of c = %c', 'cc ) ;
pdntf lnvalue of i = %d', 'ii ) ;
printf 'Vrvaluo of a = o/ol, "aa ) ;
Figue 1.4
)
Thc address of first byte is ofton known as thc base addrcss.
And herc is the output,
Though ll and rt contain ody the base addrcsses, the e*ftdssions
, ,
In the first method the 'value' of each 4crzal atgumetf in the Note that values of s and b remain unchanged even after
exchanging the values of x and y.
calling functiol is oopied into aonespondirg forr al argumcnt of
the called function. With this method, ohanges rnade to tlre fotmal
In the secold method (call by reference) the addresses of actual
argume[ts irr the called function have no effect oo the values ofthe
arguments in the calling futlction are copied into fonnal arguments
sqtual argum€nts in the calling function.
ofthe called function. This means that using the fomal argumeflts
following Eogram illustrates the 'Call by value'
in the called funotion, we can make changes in thJ actual
arguments of the calling function. The following program
r p.J,l,ff z r illushates this fact.
14 Understanding Pointers In C Chapter 1: An Introduclion to Pointers 15
fProgtam 8
./
areaperi (radius, &area, &perimeter ) i
main( ) printf ( 'Area = %f, area ) ;
{ printf ( '\nPerimeter = %f', pedmeier)j
inta= 10;
intb= 20l
areapei ( int r, ioat 'a, float *p )
swapr (&a, &b ) ;
pdntf ( "\na = o/od" ,a); 'a = 3.14'r'r;
printf('\nb=%d" ,b); 'p = 2'*3.14' r;
i
swapr ( int
*x,
int
-y And here is the output...
)
{ Enter radius of a circle 5
inlt; Area = 78.500000
Perimeter = 31.400000
t=-li
Here, we are making a mixed call, in the sense, we are passing the
value of radius but addresses of area and perimeter. And siDce
) we are passing the addresses, any change that we make in values
stored at addresses oontained in the variables a and p, would mako
The output ofthe above program would be:
the chaflge effective even in main( ). That is why when the conhol
retums fiom the function areaperi( ) we are able to ourpul the
a=20
valuos ofiare! and perimeter.
b=10
Thus, we have been able to rctum two valuos from a called
Using 'call by reference' intelligently we can make a function firnction. This helps us to overcome the limitation of the return
retum more than one value at a time, _which is not possible statement, which can rctum only one value ftom a function at a
ordinarily. This is shown in the program given below. lime
/. Program 9'/
main( )
Functions Returning Pointers
{
int radius i The way functions retum an int. a float. a double or any other.lala
float area, perimeter j tlpe, it can even retum a pointer. Howevei, to make a funcrion
retum a pointer it has to be explicitly mentioned in the calling
printf("\nEnter radius ofa circle " )j function as well as in th€ function definition. The following
scanf ("%d", &radius ) ; program illustrates this.
16 Understanding Pointers In C Chapler L An Introdu( tiott to Pointers 17
Output
(4) main0
{
floata=7.999999;
5
float'b,'c;
b=&al
Explanatioa c=b;
printf ( tu%u %u %u', &a, b, c ;
)
printf (tl%d %d 96d 96d., a.( Aa
NULL has beea defined in ',stdio.h,' as follows: .I ),.b,'c );
#define NULL 0
Output
Heroe, duiing peprocessiog NUff *,in be rrplaced bv o,
resulting into 5 getting stored irr r. 4200 42N4N0
0 24576.318115
(3) #include 'stdio.h'
maioo Explaaatioa
(
)
t
tloat.jamboee ( fod.);
float P = 23.5, 'O ,
Output q=&p;
pdntf ( tlq bebre cdt = 96u', q ) ;
Enor message: Non ponaue pointer assignment in main q=jamborBe(&p);
printf ( \q afler ca[ = %u., q ) ;
E)tpltiafion
The rcason for the eror is simple. The integers being passed
tloal 'jamboree ( foat t )
to check( ) arc collected in i and j, and then their addresses t=t+1:
Unders tatding Point ers W Chapter l: An Innoduction to pointers 23
rBtum ( r) ;
Explatatioa
)
( tpb )++
main0
{
Explatation ' int'jl
roidtun(i -);
means q
ln mrtd ). q has be€a d€clarEd as a trott pointer' lt
;; ;-G;il capable of holding the addtess of a flori tun(&j);
rrt-rnf, o = Cr'm of p' a ltoal is stored ia q and )
,fr*,i"fu "ri,t-"gl th" p"iotf( ) This is the value of q
"aat""" void tun ( int -k )
il.i.,{'i"i-urt-*t li"Erle<I.'whetr-irmboree( ) i8 called the t
ffi;:Jir;i" "X; i, -a i" *u""t.a i" At this^juncture inl a ='10;
$'e ratr the progmm '' was 54vui wnen
it I add staEment he,E *,/
r contains 5498 lwhen
,a" *" paga- this may tum our to be somc olher )
"*a"a"
lia*""1. Wr,* t i.ircremented it would become 5502 whv
.-"t* #+i S*""* . is a tro.t pointer aDd on incrmentiflg il4 Explatation
i"'iii*.rfa poin r. {re nert ll'oat which would be F€sent
'k=&a;
iL*. rt"oo. il*.
cvery Oo.t is 4 bytes lotrg The return
tl"o rett^" lhis adrlress 5502 back to EalD( \ ipff+ #rph
"tat"rnent 9) Are the expEssiotrs aod saDe?
Since a llo.t poiott is bsitrg retume4 a deElaration-.lloat
*lembore. ( flort') is necessary in main( ), whrch tolls me Explanation
clmoiler rbat dowtr the li.oe therc exiss a fitnction called
i".LiC I *rti"l *itt r€ceiv€ a tlo't poiDter and will retum No. *Ptr+ inorcments the pofut€r and oot the value pointed
a llort poirtcl. by it, whereas, +rph iacrements tle value befug pointed to
by ptr.
[Bl ANwer tb€ folowing: (4) Where can poit*€rs ie used?
the same Job as
(I ) Can you write anoth€r exEessioo which does
.-1'pE9 Explarration
{Jnderstanding Pointers In C Chapler l: An lntroductian to Pointers 25
#include 'stdio.h'
main( ) main0
{ {
int a = 10,1; float
-p'1,
i= 25.50;
\sid'k; chat *p2,,
i=k=&a; pl=&i;
j++ ; p2=&i;
k+; )
printf ( \lyou %u', i, k ) :
Explaaatiott
Unders land inE P ointers In Chapter 1: An Introduction to Pointers 27
Explanation
Explanotioa
You can t)?e the following program and step through your (I 5) Can anlthing else generate a Null pofuter Assignoent error?
progam using F8 or F7 and modtor ihese values in thi witch
window. At the point wheir one of thern chaages, you have Expla atiot
just executed a statemerf that uses a pointer thai has-not
been
prope y initialized. Yes. using a wild pointer that hsppeDs to reference lhe base
area of the data segment may cause the same error
#inclds 'dos.hi since this
would change lhe zeros or the copyright bauner Since
#include 'stdio.h' data
corruption oa staok comrption could cause an otherwise-valid
#nclude 'stirE.h'
poi[ter to be corupted and point to the base of the data
segment, emy memory corruptioD could resull in this
main( ) error
berng generated- If the poitfer used itr tfie progmrn
( slatement
thal corrupts_ tbe key values upp""r. to frur"-b""n p-p".iy
char 'ptr, 'banner ;
lnitr:lize4 elac€ a- watgh on lat poirter- Srep througn your
pr: ( char') MK_FP (_DS, 0 ) : Fogram again and watch for its value laddressj to chaige,
banner = ( char' ) MK_FP ( _DS, 4);
'dd = t;
change(c,d); )
printl ( "hBack to $rap( )....' ) ;
pdntf ( "\nAfier change( ), c=%d d=%d',c,d); (5) maino
I t
inta=5,'aa;
change (int q intd )
{ aa=&a;
intt; a=power(&aa);
printf{'ba = Yod aa=%t,a,aa);
pintf ( '\nwe are in changq )....'); )
printf ( "bAddress of c = %u Address of d = %u", 8c, &d ) ;
printf ( \nBefore interchanging, c = o[d d %d', c, d ; power ( int *ptr
= ) )
t=ci {
c=d; intbi
d=t;
b ntf (\After interchanging, c=yod d=o/d',c,d); b=
*pt'*fitr ;
) retum ( b );
)
.
i4) main()
(
intc='10,d=20j (6) maino
{
printf ( "\nBeforc s!,/ap, c = %d d = 7od', c, d ) ; inti=3;
swap ( &c, &d ); foat I = 3.50, 'plod ;
printf ( \Affer suEp, c=96d d=96d',c,d); float' multiply ( irt float ) ;
)
*dd
pmd=multiply(i,f ); A
swap ( int 'cc, int ) printf ( lnplod = %u value at addess = 7ol, pn2d, 'prod ) ; t
{ )
exchange ( &cc, dd );
) ioat ' multiply ( int ii, flo6t ff)
*cq *dd t
exchange ( int int ) float producl ;
{
intt; product=ii'fi;
pdntf ( lnprcduct = o/ou",
%l address of prcduct = product,
Sointm antflrays
What are Arrays L Tlrus. in this example perl3l rEfers to 23 and perl4l rcfers to 96,
An Array is a colleotioa of similar elements stor€d in adjacent rn general, the notatjotr would be perJil, where, I cao
take a value
mernory locatiom. An odirary variable is o@able of storing only 0.^1, 2. 3,-or 4, depe[ding on the positiotr ofthe elemenr
b€iDg
rel'erred. Here per is rhe subscripted variable, whereas,
one value at a time. Howwer, lterc arc situations in which we
subscript.
I is it!
would be wantitrg to storc mol€ than one value at a time in a single
va.riable. Supposc vr€ *,ish to store the perEeDtage marks obtained
A subscripted valiable is also calle.d atr .aEay'. Thus, an a[ay is
by 100 studerlts in m€mory. In such a case we have two options to a
collection of similar elemsots. These similar el€m"ot"
storc these marks in me.morl4 6" ufi
Itrts, or all ,lorts, or all chrE, etc. Usually, the array "orfJ
of chrrs is
called a 'striag', wherras an aray ofitts o; tro.ts i"
(a) Constsuct 100 vadabl€s to storE perceDtage marks obtaircd by iaffea
an array. Remembcr that all el€rne s of any givea array "imply
100 ditrcrent studetrts; i.e. each variable cootaining one musibe
shrdent's marks.
of the same tlTe i.e. w€ camot have e adat of l0 mmbers, of
which 5 are ltrts and 5 arp floats,
(b) CoNtruct one v{iable (called a subscript€d va able) capable
To begin with, like other variables m anay oeeds !o be declarcd,
of storing or holding all tlre hun&€d mad(s.
so thd the cotrpiler will kaow wtat tind oim *ray
an afay we waat For exaEpla, -a m* iargJ
Obviously, the s€coDd alkmative is bett€r. A simple reason for
this is, it would.b€ rnrch easier to hodle orc %dable tharl lnt ma*s[30] ;
haodliag 100 difiem,rt ya.iables. Motsov€r, there arc cartai['logios
that camot be dealt wilh, witrcut fr€ usc ofa subsctipted variable. Hcre, lnt specifies the Orpe of thc v{iablg just ss it do€s
wirh
Now a fomBl defiritioa of subccripfed variableg: A subscripted ordinary ya ables and thr word lnlrltl i! fhe trane ofthe vadable.
variabte is a collcstivc ame give,n to a 8!oup of 'similal The aumb€t 30 tells how ooy elcorfias of th€ t p€ ht wil be;
quantities'. Thrs€ similt quantities oould be percentage marks of our array, This number is ofteo howu as .dimeogioa' of the
array.
100 studcnts, q salcies of 300 €tqloyccq or ages qf 50 Thc bractct ( [ ] ) trfh lhe coq,il€r that wc are <tealiag with m
snploycrs. Whst iB iryormt is |iat the quaatitiq must be
'gimilar'. Each menrber ia lhe group is reftrred to by ite position in To fix oul id€as, let us note &*,r a few facb 8boitt ar.ys:
the goup. For ereplc, assu@ the following group of nultlbels
thrt repr€s€Et p€rs,coiagc oarts obtaircd by five stuilents. (r) Aa anay is a collectio! ofsiDila. elcmerb. It is also knowr
as a subscripted variable.
pEr = { 48, 88, 34, 23, 90 }
(b) Before using an array its tpc ad size trust be d€clarcd. For
If we w.nt to rEfer to ltG of the group, the usual
s€codd ntElbcr
cxanple,
nolation used is per2. SiEilady, the foudh rumb€t ofthe group is
refsrrEd as perr. Howwer, io C, the fourh nmber is refsrred as lnt arI3ol ;
pcrl3l. Not€ thal, itr C couttirgofeleme s begirs with 0, and mt M TIOOI ;
Chapler 2: Pointers and -Arralt: r'l
num[] = i '
char ch[25] ;
)
(c) The ftlt elemsot io the aray is numbered 0, so the last
element is I less lhatr the siz€ ofthe aray. So do rem€rEber tha! ensudog that we do not rcach beyond
the array size is entirely the Eograxnmer's botheratioo and not
(d) the compiler's.
/. Program 14
./
f Prcgrarn 13'/
main0
fDemonstralion ofcall by lefelence'/
main( )
{
(
int ij
int ma*sll = { 55, 65, 75, 56, 78, 78, 90 } ;
inti;
ini ma s[]
for{i=0li<=6;i++)
= { 55, 65, 75, 56, 78, 78, S0 } :
disp ( &marks[] ) ;
for(i=0;i<=6;i+) )
disp (&m*s[ ];
disp (int.n)
)
disp ( int 'n ) {
show (An );
t
pdntf ( "Vr.rfi', 'n ) ;
)
)
Pointers and Arrays
Atrd h€re's the output...
To be_ able to see what pointers have got. to do with arrays, Iet us
55 first leam some pointer aritlmrctic. Consider the foiowing
65 example:
75
56 f ProgEm 15 */
78 main0
78
{
90 int i = 3,'x;
floa1= 1.5, 1'
*z
char k = 'c,, ;
Chapt* 2: Pointers and Arrays 45
Observe the last three lines ofthe output. 1004 is equal to original
pdntf('Vtvalue oli= 96d", i); value in x plus 2, 2008 is equal to origitr l value in y plus 4, and
pdntf (Walue ol j= %f, j); 5007 is equal to original value in z plus I . This so happens because
pdntf (Walue of k = 9dc', k); every time a poioter is inqem€r ed it points to the irunediately
next location of its tj4,e. That is why, when the integer pointer x is
x=&i; incremented, it points to an addrcss two locatioos after the currgflt
y=&j; location, since an int is always 2 b)rtes long. Sirnilarly, y points to
z=8*; an address 4 locatiols after the cunent locatioa and z points I
looation after the cur€nt location. This is a very important result
pdntf ( t\noiginal
value in x = %u', x ) ; and can be effectively used while passing ths etrtire array to a
prinf ( 1nodginal value in Y = %u'' Y ) ; function.
pdntf ( 'hodginalvatue in z=%tt,zli
The way a pointer can be hcremetrte4 it can be deqemented as
x++; woll, to point to ea.lier locations. Thus, the following operations
y++ ; can be perfomed or a pointer:
pdntf ( lnvrNew value in x = %d, x ) : (r) Addition ofa number to a pointer. For exarrple,
printf ( 'hNew value in Y = %u', Y);
inti=4,'j,'k;
pdntf ( tNew value in z = %u', z ) ;
j=&i;
) j=i't:
2004
j=j*9;
Suppose l, J and k are storcd itr mernory at ad&esses 1002, l=j+3;
and 5006, the output *,ould be...
(b) Subtraction ofa number Aom a pofuter. For example,
Valueofi= 3 lnti=4,ti,'k;
Valueofj= 1.500000 .8i ;
Valueolk=c
(b) A pointer wben incremented alwalrs poitrts to an immediatelv element no.0 address =,1001
next location ofits qpe element no. 1 addrcss = 4003
element no.2 addEss =,{005
Suppose we have an afmy, elemenl no.3 addBss = 4007
element no.4 address = 4009
int numl]= { 23, 34, '12, ,14, 56, 17 }; element no.5 addEss = 40'11
The following figure shows how this array is located in memory. Note that the aray elements are storcd in oo[tiguous memory
locations, each element occupying two b/tes, since it is an integei
aray. When you run this programr you may get different
addresses, but what is promised is that €ach subiequent address
23 34 t2 44 56 t7 would be 2 b)'tes greater than its immediate
Eedecess;r.
400 4003 ,1005 4007 4009 4011
Our next two pograms show two ways in which we can access the
elements ofthis array. The fitst on€ uses the subscript notation.
The output ofthis prcgram wottld be: In this piogram, to begin with we have colleoted the base address
/'Program 18'i
pdntf ( \address = %u ' , &numfl );
pdntf ( "element = %d',I );
main( )
{ On inqementing j it points to the next mernory location of its O?e,
int ntim[] = {24,34, 12,44,56, 17 }; that is location ao. 4003. But location number 4003 contains ihe
inti=0,-j;
seoond element of the array, therefore when the prltrtf( )
*l statements arc executed for the second time they pdnt out the
j = &numl0l ; f 6lign address o, zelofi elemenr
second element ofthe array and its addE$s (i.e. 34 and 4003). This
while(i<=5) oontinues till the last element ofthe array has been p nted.
{
printf ( 'haddrcss = %u ' , &numll ) ; Obviously, a questioa arises as to which oflhe above two methods
pdntf ( "element= 96d', I ) : rhould be used when? Acce$sing a.I:ray elemeds using poi
r!\!!yq faClgl th!4 qno€ssftg lhein ljr subscripts. However, ftom-
i++ ; lhc point of view of convenience inligramming we should
j++ ; f increment poinler b point lo ne* Iocalion '/ observe the following:
)
l Anay elements sholld qe accessed using pointers, if the elements
t!!.19-!Eg!!!!99r4 a fixed order, sav &om be EiniGind. or
The output ofthe program would look like this: Cof end to besinnliE, or=-ry d temenr
rldfinite logic.
address = 4001 element = 24
address = 4003 element = 34 rlt would be easier to access the elementjfgilgj lubrDriptjfltrEre
address = 4005 element = 12 ,b@"u."
address = 4007 element = 44 llrc, accessing the elements by pointeN would work faster than
addrcss = 4009 element = 56 r atr ltsc ripts.
address = 4011 element = 17
50 Undersnnding Pointers In C
The output ofthe program would look like this: Look ar rhe pritrtf( ) statemelt...
'I1rus. 1234 is storEd in stud[0][01,56 i8 stored iD studlollll and we expect the Od elemetrt to get priated aod tbe 06 elernent is a 1-
t" fnt above arraogcment highlights the hct that ofa-two- D anay. We know that just m€trtiodry a l-D array gives its base
"o.
dime[sional array i6 trothing but a collection of a number one- address. Herce the printf( ) would print base ad&ess of the 0d l-
dimensional arrays plaoed orc after oother' D anay. Similarly, stud[l] would give address of lr l-D aray and
so otr.
Rememb€r that the alraryem€|trt of r 2-D array
into row and
,oi.".a i" oaly conceptually ttue' This is because in memory This fact can be illustrated by the fo[owing program:
tfr"." no -tit *A cohoms' to memory whe&er it's a
l-D or a
i-o "* At at-*ta are stolpd in one continuous chain' .r Pl0onn22'l
"r-y . /f ReferfgurB 2.3 given in 0E pGvixBsectbn'/
\Vl maino
Pointers and Two Dimensional Arrays
poinlEr notatioil'
Lt' in, rtuotsltzl= (
Catr we not tef€r elem€Dts of a 2-D afiay usitr8 ( 1234.56 ),
the wav wc did itr ooe{imeDsioDal anay? ADswer is y!s' only me
11212,331,
prociure is slightlv dimcdt to urderstand- t'et us see how' { 1434, 80 },
{ 1312,78},
The C language embodies euousual but pow-€'rful capability: it { 1203, 75 }
each rortr ot
treat pirrs of an anay as aEays' MorG 4ccifiGally' ];
".n
,**"--a]i.*i"J * & thought as a one-dimensioDal inti,j;
"t-i'
arrav. Ihis i8 a very iEportaut fact if we wish to access aray
el#ents of a twodimersioul array using pohters' for(i=0ii<=4;i+i)
pdntf ( "hAddress o, ,6d fi 1D any = l6u', ;, sM[l 1 ,
Thus, fie declaration, )
'(stud[2] + 1 )
Address of 1 th 1-o aray = 4005
'(-(stud+2)+1)
Address of 2 th 1-D aray = 40 )
Addrcss of 3 th 1-D aray = 4013
Using *ese concepts the following Eogram priDts out each
Address of 4 th 1-D an-ay =,1017
element of a two-dimensional
aray using poirter notation.
Let's figure oul how the progmrn works. Once the 2-D array is
declared, there orwards stud is aeated as poirter to zeloth element
f Pnlftn23'l
main0
of the 2-D array. Heoce the exprglgiorL4itud-+-0 L€iles tN the (
ed.iress
adrl'ess of the 0"
Ge 0d elemeot of the
Ee 2-D atay,
aray. Naturally. lhe int studl5ll2l =
I element. Bu t the Orh
{
{ 1234, s6 },
elemefi ofthe 2-D array is a l-D aray- And on mentioning l-D
11212,331,
array we get its base address. Heqqg j(!]E4! jllLLtygqlhe base
{ 1434, 80 },
addrcss ofthe 06 l-D array. Referring to Figure 2.3 this rums oul
{1312,781,
io be 4ffiI:Timilady, caD you interpret the meaning of studlll { 1203, 75 }
(which is nothiDg but *( stud + I ))? rtud gives address ofthe 0d ),
elem€nt, herce st d + I worl.l give lhe adjress of the ls' element inli,jj
and r( stud + I ) would give lhe first alemeEt. Since the l"'
element is nothilg but a l-D array, and on mentioning the l-D for(i=0;i<=4;i++)
array we get its base ad&€ss, *( stud + I ) gives base address of lsr t
t-o,arravW)) printf("h');
(j= 0;j<= 1 ;.i++)
would givs base addtEss oft- l-D anay. for
.l printf("70d','(-(stud+i)+j));
Now, we have beetr able to reach e3ch hdividual row. What
remains is to be able to rcfet to itrdividual elernenrs of a rcw. )
Suppose we want to rEfer to the elerneDt $hd[2][U using pointers.
We know (Aom the above program) that stud[2] would give the And here is the oiitput...
ad&ess ,1009, the address of lhe second one-dimensional array.
Obviously ( ,1009 + 1 ) would give the sddEss 4011. Or 1234
1212
Gtudt2l+f) would givG lhc addr€ss 4011. And the value at this
addrcEs cari be obtaircd by usitrg the exPr€ssioo '( stud[2] + I ).
1434 80
1312 78
But, we havc alncady mt€d wtilc learuing l-D &rays that numlll .l203
is sam€ as r(E!n + l). Simi :( ttd[2] + l) ie same as,
75
srtdt2ll1
whereas, q statts pointing to the text 1-D aray of 4 integers.
Pointer to an ArraY Poilter to an array is very usefirl while passiag a 2-D array to a
furction, as we nould s€e in the next sectioa.
The way 1,,e cao have a pointer to atr integ€i, or a pointer to a float,
*" ulio have a pohter to an array? The answer is yes Passing 2-D Ariay to a Function
"u,
Declaration of a pointer 1o atr array, however, is a little clumsy
*q
For examole. the declaration Lrt ( )l4l Eeans tbat q is a poitrter There are thtee ways in which we can pass a 2-D almv to a
,o on orr& of4 itrtegers. Let us use this pointer to an army in a function. These at€ illustrated iD the following program.
Eogram. Herc it is. . .
f Program 25 '/
I Pmgram 24 '/ f Three ways of accessirE a2-D a,ra(.'l
main0 #include <alloc.h>
{ main0
iit alll4l= { (
5,7,5, 9, int aB[ ]E_ {
4, 6, 3, 1, 1,2,3,4,
2,9.0,6 5, 6, 7, 8,
); 9, 0, 1,6
int'p; );
int ('q )l4l ;
clrsc( );
p=(int )a; disphy (a,3,4);
q=a; show ( a, 3,4 ) ;
pdnt(a3,4):
pdntf ( 1n%u %u', p, q ) :
)
p++:
display ( int 'q, in row ir[ col )
pdntf ( 1no/ou %u', q);
P, {
) inti,j;
And here is the output... for(i=0;i<rcy;i++)
{
65500 65500 for (j = 0;j<col;i++)
65502 65508 Pnntf ('old',' (q+ i'col +i ));
To begin {.ith both p and q contain the same address 65500' printf('\n');
However, p is an io&ger pointEr, whercas q is a pointer to an array )
of4 intege$. Heoce on incremetrting p it pohts to the next iirteger,
60 Understanding Pointets In C Chapter 2: Pointers and Arravs 6l
printf (1n' ) ;
) 1234
5678
show ( intfq)141, int roll, int col ) 9016
{
inti,j; 1234
int'p; 5678
9016
lor ( i= 0; i< row;ir-i )
{ In the displd ) ftactioa we have collected the base address of the
p=q+i; 2-D array beiag passed to it in an odinary itrt pointer. Then
for(j= 0;j<col;j++) through the twoJor loops using the expression * ( q + i * col + j
pdntf ( Yod ', ' ( p+j) ): )
we have rcached the appropriate ele rent in the arty. Suppose iis
equal to 2 aod j is equal to 3, then we wish to reaih thi element
pintf (t'); r[2] J3l- Let us see whe6er the expression * ( q + i * col + j does
) )
prinlt('\n');
grve thrs elemenr oihol Refer Figure 2.4 !o uDderstand this.
for(i=0;i<rorv;i++)
{ Figure2.4
fq(J=0;j<cot;j+)
pdntr ( '96d ', q[][! ) ;
l'he expression * ( q + t * cot + j ) becomes * ( 400f + 2 * 4 + 3
'l'his tums out to be * ( 4001 + ll ).
pdntf('Vr'); ). Since 400I is address of an
inleger, * ( 4001 + tl ) tums out to be * ( 4023 \. Value at this
)
pdntf("h'); oddress is 6. This is indeed same as e[2][3]- A more general
lbrmtrla for accessing each array element would be:
)
r(
And here i$ the output. . . base address + row no. t no. o, columns + column no.
)
How would you reler lo the array element I in the above array?
);kL\
p ntf { '\n%u', 'a + I
printf('h%u', *a + 1);\ \'
The first subscript should be [2], since the element is in third two- printf {"\n%d', *a + 1);j .
dimensional army; the second subscript should be [3] since the )
element is in fouth row of the two-dimensiotral array; and the
third subscripl should be [l] since the element is in the second Figue 2.7 shows the arangcment ofthe 3-D aray in memory.
position in tie on€-dimensional a.ray. We can thercfore say that
the element I can be referred as, arrl2Jl3Jll I. lt may be nored here
that the countirg of alray elements even for a 3-D array begins
wirh zero.
06 2-D arlzy-+- t, 2-D array
21417 8 3 4 2 2 2 3 3 4
Can we not rcfer to elements of a 3-D array using the pointer
notation instead of the subscript notation? Certainly. Let's first
104 106 loa ll0 ll2 ll4 116 I18 120 t22 124 126
begin with a simple Eogram-
-/ Figure 2.7
/t Program 26
maino And here is the output ofthe prografi...
{
int aPl[3][2] = .l04
{
{ t0r
{2.41, t0{'
17.8'^). I
{3,4} ilt
], t0r
t0r
66 IJnderstanding Pointers In C
J
),
Referring Figure 2.7 it's not difficult to imagirc why the first {
2,3,5,7,
prtntf( ) pdtrts out 104. However, the outsut of second and thftd 4,3,9,2,
pritrtf( ) is a little supiisiry. Let's try to undflstaod it 1,6,3,6
Each element ofa 3-D aray i8
au'ay is a 2-D aEay. Once the 3-D
]
);
deolared a is treated as poh&r to zercth eleiaent of the array.
Hence *a gives the zercth element whioh is .2-D array, We know clrcc( );
that on mentioning a 2-D array we get its base address hence the display (a,2,3,4 );
second f( ) outputs 104. what about tfre exprEssion **e? *r
pri show (a, 2, 3,4 ) ;
gives poiater to zeroth element of the 2-D an'ay, h€na€ **a would print (a,2, 3,4 );
give the zeroth eleme . But the zetdflr elernent ofthe 2-D aEay is getch0;
a 1-D array. And oa mentio[iog l-D array we get the addrcss of its )
zeroth elemeot, Heace **e also yieltts 104. Now you can guess
that ***a would give the €lernent at ad&ess lo4, i.€. 2. Let's Dow display ( int rq, int ii, ii, int kt )
try to alalyse the output ofthe next prirtf( ) statement a gives the ( 'nl
aidr".r oi znroflr i-D arra% therefore, + would give the . I int i, j, k;
addrcss of fiIst 2-D aray, which as per the fgure is 116. Can you for(i=0;i<ii;i++)
now imagine the output ofthe rcst ofrhe prhtf( )s? Try it. {
br(j= 0;.i<X; j++ )
(
Passing 3-D Aray to a Function for(k=0;k<kk;k+t)
pnnf ('%d','(q + i'jl'kk+ j'kl+ k) ;
)
There are thrce ways i4 which we oatr puis a 3-D atray to a printf ( 1ll" );
function. These are illustrated below. )
printf(1n');
f Pmgram 27
./
)
f Three ways of passing a $D anay b funclixl '/ pdnf ( 1n" ) ;
main0 )
(
int i, j, k; show ( inl ( -q )Bl[4], irf ii, imii, int kk ]
jnt a[2]Pl[4] = { (-
{ int i, j, k;
1,2,3,4, int'p i
5,6,7,8,
9,3,2'1 for(i=0ji<ii;i+r)
t
Understanding Pointers In C
Chapter 2: Pointers and. Arrays 69:
932'l
for(j=0;i<ji;j++)
{
p =c[][]; 4392
for(k=0;k<kk;k+) IOJD
Pdntf ( '96d ', '( P
+ k) ) ;
printf( 1n' ) ; 1234
) 5678
printf('1n'); 9321
)
) 2357
4392
/ print ( int q[ ]l3l[4], int ii, inl ii, int kk ) 'I 636
"r'1
int i, j, k; The wotking of lhis progre ir same as that of kogram 25
for(i=0;i<ii;i++) discussed earlicr. HeDcc all ftar I yrduld do here i,s explain how q
{ has been declared in each fimctiol
forlj=0;j<ii;j++)
{
for(k=0;k<tk;k++)
pdntr ( %d '. q[]D[{ ) ;
pnff (\l" ) ;
41lq )t3lt4l 'qis a poitrb to a 2-D snv of3 rows md 4 columns
)
pnnf('1n') ;
iDt qt lt3l[4] q is a]6iqt€I ro a 2-D sray of3 rows ird 4 coluotrs
) Table 2.1
)
Returning Array from Functiin
And h€re is the output...
Now that we tnoq, how to pass a 2-D ot a 3-D aray to a firnotion,
123 4 let us find out how to r€tultr a,l array ftoItr a fuDotio[ Therc are
5678 again three methods to aohieve this. Suppose we wish to retum a
932'l
2-D anay of integers from a function we caa rcfum the base
addrcss ofthe array as:
2357
4392 - A pointer to an integer
1636 - A pointer to the zeroth l-D array
1294 - A pointer to the 2-D aray
5578
This is shovn in the followitrg ptogram. The firdctior futrl( )
b = fun2( ) j
reltrms the base addrcss as pointEr to integor, the function fuD2( )
rgturns it as pointer to zerolh l-D aray, whereas fun3( ) retums it
printf ( "\nArEy bl
as pointer to 2-D array ofhtegeN. Note the prototype declarations l[ J in main( ):h. ) ;
for(i=0;i<ROW;i++)
of the functioDs caefi ly.
{
p=b+i;
f Prcoram 28 '/ */ for ( j= 0; j< COL 'i++ )
I ways of lBtuming a 2-D aray
Th;e tun a funclion
#defne ROW 3 t
prjntf(t/od',.p);
#defne COL 4
p++;
main0
)
{ pnntf ( "Vr') ;
int i, i; )
getch0 j
tint'a;. c= tun30;
int'tun10: /
printf ( "h&ray d l[ in mdn(
int ( 'b )ICOLI;
I ):W ) ;
for(i=0;i<ROW;i+[)
iirr ('f,ii'20 )poll;
-p; {
int
for(j=0'j<COL.++)
pdntr( %d., (.c)[ilUI) ;
int ( 'c )lRowlpol-l :
int ('tun3( ) [RoWIcoLl ; pintf('\rf);
)
cllEc( ); getch0 j
a=tun10;
)
pdntf ( hAray allll in mai( ):W ) ; Int.fun10
lor{i=0;i<ROW;i+r) (
l' shlic int alRowlmrl =(
for( i= o;i< coL:j+) 1,2,3,4,
printf ('%d';'(ar i'col+ j )) :
5,6,7,8,
9, 0, 1,6
pdntf(1r'');
);
) inti,i;
setch( ) ;
"2 Understaading Pointers In C Chapter 2: Pointers and Arrays 73
[ I in tunl( )M );
pintr ( lnAmy a[ inti,j;
for(i=0;i<ROIIV;i++)
{
printf ( 'hA;y cl II I in tun3( ):h' ) ;
tor COL 'i++ )
(i = 0;i< for(i=0;i<ROW;i++)
pintr ( 'r6d ', al i lli I ) ; {
for(j=0;i<COt;j++)
pintf( 1n' ) ; printr('Y!d', cl i ltj I ) ;
)
retum(int.)a: pdntr ( 1n');
) )
retum ( int (' )[ROl'vllCOL] ] c ;
int ( 'tun20 )lcotl )
{
shtic int blRoll'{mq ={. And here is the output- . .
9.4' 6' 4,
1,3'2'1, Araya[]llintunlo:
7'5, 1'6 1234
); 5678
inti, j ; 9016
tAray bt l[ I in tut2(
pdntf ( )rtr' ) ; Arlay al l[ ] in main( ):
for(i=0;i<Rqw:i+l) 1234
{ 5678
tu (i= 0; i< col;F ) 9016
pintf ( *r6d btilil );
Anay b[][] in luo2( ):
"
pnntf ( t'); 9464
) 1321
rctum b;
)
Anay b[][]in main( ):
int ('fun3( ) )[Rou,tPOLl 9464
{ 1321
static int ctRolfulcou = {
'l'
7516
6. 3, 9,
2,1'5,7, Anayc[][]in tun3( ):
4,1,1,6 6391
): 2157
lJ"dntnndl!E!9!!!9o I" C Chqtei 2: Pointers and Arrays Z j
4116
int ( 'c )lRO\aTCOLl ;
Aray c[ ][ ] in main( ):
- int ( 'tun30 )lRol'uporl;
63S'l int.p;
2157
int ( 'd )lSEIllRoW[coLl;
4116 .fun40
int ( )lsEr]lRovupoLl;
Returning 3-D Array from a Function clrsc( )j
a= fun10;
lf you have undelstood how to retum a 2-D aray ftom a functio[,
on similar liaes wc can rclum a 3-D array ftom a functioa The pdntf ( lnAnay a[
I[ [ I in mai( ):W ) ;
four possible *ays to do so would bG to retum the base address as: for(i=0;i<SEI;i+i)
{
- A pointq to ali integer
for(j= 0;i < ROW; j++
)
- A pointer to ihe zeroth l-D array
{
- A pointerto the zercth 2-D array for (k= 0;k < COL;k+r,/
- A poitltcl to the 3-D ariay pdntf('96d','(a + ir RCIW'COt +j. COL + k )) j
Given below is the pDgram, which ifiplemeDts these four ways of printl ( 'h') ;
pdntf(1n');
f Program 29 '/
f Four ways of retuming a $D aray film a funclion .l )
getch0;
*idefne SET 2
Itdefne ROW 3
b = fun2{ ) ;
#deline COL 4
printf ( '\nAn-ay b[]Ull in mJn( ):h' ) :
maino
fol(i=0;i<SET;i++)
{ (
inti,j,k; p=(inl,)(b+i.ROlfl);
for(j= 0;i < Row;.1++)
int'a;
int-fun'lO; {
for(k=0;k<COL;k+r)
.b {
int ( )lcotl ;
pdntf ( '%d ., .p
int ( 'tun20 ){coLl :
) ;
p++;
76 Unilerstanding Pointers In C Chapter 2: Pointers and Arrays 77
for(k=0:k<COL;k++)
) pdntr('%d ', (-d )[i][i l[ k l);
pnntf (1n');
pdntf ( 1n');
]
)
pintf('h');
printf("\n");
)
)
getch( ) ;
ttro; )
c= tun30;
int. tun10
pddtf ( '\nAray c[ ][ ][ I in main( ):W ) : {'
for ( i = 0; i< SEI; i++ )
inti,j,k;
( static int alSEIllROVtIllCOLl = {
p=(int')(c+i); {
for(i=0;j<ROW i+t ) 1,2,3,4,
5,6, 7, 8,
I
' for(k=0;k<COL;k+[) 9,3,2,1
{ ),
pnntf ( '9{d ', 'P ) ; {
p++; 2,3,5,7,
.4,3,9,2,
) 't, 6. 3. 6
pdntf ( 1n') ; )
) );
pnntf (\l') ;
pdntf ( "hArmy a[ ]l lll in tunl( ):Vr' ) ;
for {i= 0 ; i< SET; i++ }
)
getch( ) ;
{
for (i = 0 ;j < ROW; j++ )
d = fun40 ;
{
for(k=0;k<COL;k++)
printr { '%d ', ali ltj llk
p 'hAray d[l[l[] in main( ):W ] ;
ntf ( I);
for (i= 0 i i< SET;i++ )
printf(ln'):
{
for (j = 0 ;j < ROI,V ;j++ ) )
(
78 Understanding Pointers In C Chapter 2: Pointers and Arrays 79
I
pinf ( 1Il');
) lnt('tun40 )lsErllRorulcoLl
(
retum (int {')[COL])b; int i, j, k j
l slatic int dlSE IllROWlCoLl = {
{
80 Understanding Pointers In C Chapter 2: Pointers and Arrays 8l
3, 1,8, 5,
9, 6, 5, 2, a[][][]
Aray in main( ):
2,0,1,6 1234
), 5678
{ 932'l
7,3,2,7,
1,4,2,3, 2357'
'9,
1,0, 6 4392
) 1636
);
Anayb[I][Iin tun2( ):
printr ( "\nAray d[ ][ ][ ] in tun4( )ln' ) ; 9464
. for ( i = 0 ; i < SET ; i++ ) 1321
75't 6
{
lor (j= 0;j< ROW jr+)
{ 6391
lor(k=0;k<COL;k++) 2157
pintf ( '96d ", dliltjllkl); 4116
3185
Aray a[][][] in tun10: 0652
123 4 2016
5678
9321 7 327
1423
2357 0106
4 392 i
1636 Aray c[][][]in m;in0:
82 Understatding Pointers In C Chapter 2: Pointers and Arrays 83
3185 fPmgram 30
.i
9652 main( )
2016 {
int 'ar[4] ; f fiay of inhg€r poinbls '/
.
7327 int i= 31, j= 5, k = 19, t= 7t, m
1423
9106 an[0] = Ai;
an[1] : &.i '
Aray dll[]ll in tun40: anl2l = &k;
1705 art3l = &l ;
2391 for(m=0;m<=3;m++)
5116 pdfltf ( 'h96d', '( adml) );
)
cJ I /
1423 Arld here is the ou&ut...
31
Anayd[][][]in main( ): 5
1705
2391 71
5116 0'
5317
1423 kl
7 216
l-,,1
4008
l--;l
5116
l--rl l=-l 6010 7I l8
Array of Pointers
The way there,can be an array of ints or an aray of floats,
similarly there can be an array ofpointe$. Since a pointer variable
always ooatains an address, an array ofpoiaters would be nothing ad01 adll a"IL2I ant3l
but a colleclion ofaddrEsses. lae adclresses preselrt in the alray of 4008 5116 60lb )r ra
pointers oan be addresses of isolated variables or addresses of
array elemerfs or any other addresses. All rules that apply to an 7602 7@4 7@6
ordirDry array apply in toto to the array ofpointeN as well. I think
a prograrn would cldiry the concept.
Figure 2.8
84 Understanding Pointers In C Chapter 2: Pointers and Arrays 85
Figure 2.8 shorns the contents atrd the arangement of the array of Other way rouad there alwa]rs exists a possibility that when you
pointeN in memory. As you cal obwrve, arr contains addresses of rrn the program you Deed !o store more ihatr 100 student's marks.
isolated lDt variables i, J, k and l. The for loop in the plog1am In this case the aray would fall short in size. Moreover, llpre is no
picks up the addresses present in arr ard pdEts the values prcsent way to inqease or decrease thqauay size-dudng-crGeq![q4-!t][ the
at these addresses. program. l,
other words, wheo we use rmys statil memorv
al.J99g!9!-!4Eq_p&qe. What if we wart to allocate niemory only at
An array of poiaters can evetr contain the addresses of other rhe dme of executioo? This -is datrc__Jsl[g* standard [trary
arrays. The following plogram wouldjusti! tltis. furctions mill^.( ) and catloc(J. Since these tunotioos allocate
memory on the- fly (during executiotr) they are-often tno",t1 as
/' Pogram 31 '/ 'Dyramic meinorjr allocation functions=) L6t us now see a
maino program, which uses the corccpt ofd)mamic memory allooation.
t
static int all };
= { 0, 1, 2, 3, 4 f Program 32
ti
shtic int'p[] = {a, a + 1, a +2, a +3, a+4 }; #incude ?lloc.h'
main0
printf ( ln'/ou %u 96d', p, 'p, '( 'p ) ) ;
{
) hl n, avg, i,-'p, suo = 0;
I would leave it for you to figurE out the output of this program. pintf ( \Enter tle number of studenb ' ) ;
An array of point€rs is very popularly us€d fol sioring several scanf('%d', AD);
strings in manory, as you would see in tlre next chapter'
I p : ( imr) rnathc (n|2) ; ly
Dynamic Memory'Allocation ir(P==xuLLl
{
Coosider the array declaratioi,
pinu (
eit(
'h ---
lemory allocaton unsuccessqE) ;
) :
int ma*s[100];
)
(1) main0
(
.
int a[] = { 10, 20, 30, 40, 50 }
integgr pointsr.p. Sfuce mr[oc( ) Etums a void pointcr we have intj;
t r""ur[a it into aa integer poiorer. lo Ee first for looE-!!]iIJ tor(j =p ;j < 5;j++ )
ti-"ii6-i"ttt aritlrne6rc
keyLoar{ulqlhe rn.-ory
we tave storrd the marks ent!:red from
-that
h* b""n allocated. In the tecond
t/ printf('hyd.,t);
for loop-we have 4ccessed the same values to fitrd the avemge a++;
marks. )
)
The calloc( ) functioos works exactly similar to Erlloc( ) except
for the faot that it needs tw-o atguments. For example, O tput
inl'p; Emr message: LvaftJe tequirEd in fundfun main
p= ( int') calloc ( 10, 2 ) ;
Explanation
Here 2 indicates lhat we urish to allocate m€mory for storing
integers, (since an integsr is a 2-byte eDtity) aDd I0 itrdicates that
we-Gnt ro resEE e spaqg l&E-$q!El!!@g!ryl ADofher minor Whenever we mention the name ofthe army, we get its base
differeDce between mdto( ) and crnoc( ) is tbat' by defaulrlllhe l[erelore, firsltt!rc though
address. Therefore, trslttll!
flrcugh the loop; the pritrtf(
Dritrd( )
memory Sn co should print the value at this-bae€ ai[li&-s.-fr;iE ls no
ty dtoi@s' :Ers. wA& u!!g thrse problem up to this. The @
ii"i""-i-r.",*.*d 6^
oat attocatea s11 ies ln tEe oext statement,
tr" GpnFit-*" an allav-
begimiggof -*c'@lgaur. the only thing thai it l€rnembers about an array oace declared
is jls base address. And a#
aflgEplE_!9_f,tralgE this base
aJdrbss, wfuch C wodt allow befause itirdoes so, ir would
be uflable to remember the begirming of the array. An]thing,
which can change is called lvalue in compiler,s language.
Since value ofa cannol be changed though +, it flashes the
error saying 'Lvalue requircd' so that + oper"ator can change
it. .
Understanding Pointers In C Chapter 2: Pointers and Arrays 89
88
Outpat
(2) maino
{ 100 300
foat all = { 13.24,1.5,1.5,5.4,3.5 };
ioat l, 'k;
Explanation
1j=,;
k=a+d;
j=j'2i n[ ] has bein declared as an array capable of holdirg 25
k=kl2', elements [umbered ftoln 0 to 24. Then-100 and 200 are
printf ( 1n%f%1, 'j, 'k ) ;
assigned to n[0] and r[Zl resp€otively. Thetr comes the most
I impolant pa prhtf( statemed Wheaeyer we
)
-the
mendon the name of the array, we get its base address (i,e.
Olttpu, address of lhe zercth elqlre of the array). Thus, *n would
give the value at this base addness, which itr this case is 100.
Eror message: lllegd tse ol Finler in tunction main This is theD prhted out. Look at the rcxt expression,
Explatatiott -(n+24)+'(n+0)
{5) main0
Output {
char a{l = "Visual.C++' ;
10 20 30 40 50 char'b = 'Visual C+' ;
printf('\no/6d %d', sizeol ( a ), sizeof (b ) );
Expldnatio pdntf ( 'ln96d 96d', sizeof ( 'a ), sizeof ( 'b ) ) ;
)
Fi$t look at Figue 2.9. The aEay elements are stored in
cotrtiguous memory locations ard each element is an integer, Output
hence is occupying 2 locations.
11 2
11
b[0] btu bt2l bt3l bt4l
Explanation
l0 20 30 40 50
4lnm 4n0/. 4006 4008 4010 slzeof reports the m[nber of b5rtes occupied by an entity in
memoiy. The array r is ft,ported to be of ll
bytes because
there is a'\0'sitting at the end. b is a pointer h-ce its size ;" I
Figure 2.9
b)ts-5 atld *b both yield a charactei'V', whose size is one
The expression &b[4] gives the address of b[4] (4010 in this b)4e.
oase)- From this addEss ifwe zubtract 4, we get 4002 Or did
you expect to get 4006? Remember that by subtracting 4 fiom (6) main0
4010 what ltre mean is ge ss ofan integer, which is {
4 integeE to the left of the integer whoG-addii:ss is 4010. f Assume arEy begins at addess '1200 '/
No$r', address of the i teger, whibh is 4 htegers to the left of int anll = {2,3,4, 1,6 );
the irteger whose addrcss is 4010, is the ad&ess 4002 This pdntf ( '%u %d', an sizeol ( ar ) ) ;
addre6s, 4002, is storcd in k, whioh has been declarcd as a )
variable capable of hokling an integer's address. First time
though th€ for loop *k would result into 10, i.e. value at the Output
addrc6s co ain€d in k k+ then inclements k suoh that it
oontains the address of the oext ht€ger, i.e. 4004. Next time 1200 10
tlrough th€ for loop *k would yield the value at address
contained ia k, i.e. value at the address 4004, which is 20' Explanati6n
Similarly, rhe loop priots out the Iest of the elements of the
altay.
92 Understanding Pointers In C Chapter 2: Pointeis and Ar41y5 93
(7) bqlafiation
maino
{
f Assume a.ray begirE at addEss 65486 '/ Name of a 2-D arr.ay always acts as pofuter to the zeroth
intar{l= { 12,14, 15, A,45}; element of the aray. Since the zeroth element of our 2-D
pdntf ('%u %u', ar, &ar); 6 aray is l-D array of4 inlegers, a acts as pointer to this zeioth
printf{'%u %u'. ar+ 1. &ar+ 1):'t 1-D aray. Hence a+l gives us the ad&ess of the next l-D
)E- array, i.e. 65480.
Output The expression &a + I yields 65496. i-e. rhe address of the
next 2-D array of 3 rcws and 4 columns.
65466 65486
65488 65496 (9) maino
{
Explahalion f Assume array begirE at locdion '1002'/
int a[3][4] = {
1,2,3,4,
Both arr and &.rT yield tire base
addless of the array. 5,6,7, 8,
However, rrrtl
gives 65488, i.e. the address of the next 9, 10,'11,12
integer. However, &rrr + I gives 65496, i.e. the address of 1;
the next array ofs inl€gers.
printf ("Vt%u %u %u', a[0]+ 1,'( a[0]+ 1 ],.('( a +0 )+ 1 ));
(8) maino )
{
I Assume array begirE at ddless 65472 '/ - Output
int al3il4l = {
1,2,3,4, 1004 2 2
4,3,2,1,
7,8,9,0 Explanation '
)'
pdntf ('h%u%u',a+ 1, &a+ I ) ;
)
94 Understanding Pointers In C Chapter 2: Pointerc and Arrays 95
A 2-D airay is a coll€ction of several l-D arrays. Name of a Here, in ptr we bave stored address of l. Then we have
2-D aray always acts as pointer to zeroth elemeat of the passed ad&ess ofptr to fun( ) and collected it in a pointer to
almy. Hence, a acts as pointer to the zeroth l-D aray. an itrt pointer- Dereferencitg this pointet yields l.
The expression r[0] + I is hterpreted by the compiler as *( a ('11) maino
+ 0 ) + l. This is same as *a +1. The expression *a gives {
1002. Thercfore, *e +1 would give the address of the next f Assume a.ray begins at location 1002 */
integer, i.e. 1004. Since a[0] + r yields 1004 *( a[0] + 1 ) int a[2]Fl[4] = {
would yield lhe value at address 1004, i-e. *( al0l + 1 ) can (
be expanded gs *( "( a + 0 + ). Hence, both the
) I 1,2,3,4,
expressions would yield the salne result, i.e. 2. 5, 6, 7, 8,
9,1,1,2
(10) main0 ),
{ {
int al3l[4] = { 2,1,4,7,
1,2,3,4, 6,7,8,9,
4,3,2,8, 0.0.0.0
7, 8,9, 0 )
); I'
int'pf; *a, *a, *a
ptr = &a[o]pl ;
prjntf ( \i%u %u %u 96d', 4 );
lun ( &pt ) ; )
)
Output
tun (int
*p
)
{ 1002 1002 1002.'l
printf ( 1nyd', 'p ) ;
) Explan .tio.,
Output - The expressions a, "a, *ra, would give the base addrcss, i.e.
1
1002, wher€as the erpr€ssiol ***. would give the value at
ad&ess 1002,i.e. l. Note that the expression .[0][0][0] is
expadded into *( r( *( a + 0 ) + 0 ) + 0 ). This is same as
Explanation
(12) main( )
97
E
401 b
f, I
bb
Figure 2j10 [ 4oo, I b--,[ 4oM I
(14) main( )
Figue 2.1I
{
int alsl = { 2, 3, 4, 5, 6 }; While caling charye( ) we are passing the base address ofthe
inti; aray, which as per Figure 2.ll is 4002. This address is
collect€d in b in the functioo change( ). Then the oontrol
change (a ); enters the for loop, where we meet the explession *b = *b +
lor(i=4;i>=0;i-) 1- This means rcplace the value at the address contained in b,
pintf { 'Y"d ', a[]) ;
with value al the address contained in b plus 1. Every time
) b+ is executed, the address ofthe trext integer gets storcd io
int'b
b. Thus, using the address stored in b, we get an access to
change ( )
aray elements that are now changed to 3, 4, 5,6 and 7. O\ce
{
inti; the control comes back from change( ), the current array
for(i=0;i<=4;i++) contents are then printed out ftom end to begindng through
the for loop.
t
100 Understanding Pointers In C Chapter 2: Pointers and Arrays 101
Output
pts pt
01234
f eoor I o*, frooo I
Elplanation
FigtuIe 2.12
Refer to Figue 2.12 lot a better utrderstanding of the
(16) main0
pIOgram.
(,
Here ptr has been dectared as an integer pointer, i.e a int arl l= {0, 1,2,3,4};
variable capatle of holding the address of art integer. In the int i, 'ptr;
for loop, irl the initialisation part, this ptr is assigned the for (pb= &ar40l, i= 0; i<= 4 ; i+| )
address of the zeroth elernent of the integer aEay Suppose prinf ( %d ', ptfl ) i
this address tums oul to be 6004. Then address of the first )
element of the array would be 6006, address of the seoond
element would be 6008, and so on. In the conditioa part of the Output
for loop, the address storcd h ptr is compared with the
addrcss of the foufh aray elemen! i.e. 6012. Sirce for the 0123 4
first time lthe, conditioa is satisfied (shce 6004 is less than
6012), the'cotrtsol reaches pritrtf( ) where the value at address Expla atiol .
6004, i.e. 0 gits pinted. After executing priutf( ) the control
reaches pff+, where ptr is incremented such that it contains
In the initialisation part ofthe for loop, multiple initialisations
the addrcss ofthe rext integer. Since the next integer is stored are being done. Fi$tty, ptr is set up vith the base address of
at 6006, pf now contains 6006. Once again the condition is the alIay and then i is set to 0. Since 0 is less than 4, the
tested- Since 6006 is also smaller lhar 6012, the conditiofl is condition is satisfied for the first time atrd the control reaches
satisfied honce the printf( ) prints out the value at 6006, i.e. l. printf( ). Here the value ofthe exprcssion ptr[iJ gets printed.
And then pffi is executed again so that it corltains the
102 Understanding Pointerc In C
Chapter 2: Pointerc and Arrays t03
Now is nothiDg but r( ptr + i ). Sipce ptr coDBins tle
ptrlil
the initialisation part, p is initialised to trc base address of the
base address of the arr6-yl ptu t I ) would gi-E the address of
array. whereas i is initialised to 0. Afier these inirialisations
the id irteger 8om the bas€ ad&ess. Since i is going to vary
the cortrol rcaches the conditiotr. The condition is a little
fiom 0 to 4, this would give addrcsses ofo", l''.2"o. 3'o and
complicated so let us isolate it for a clearE u[derstanding.
46 integers ftom the bas€ addE$s of the aray. Naturally, the
exFession *( ptr + i ) would give values at these addrcsses. p+i<=alr+4
Thus, the for loop would print out all the array elements.
Here + enjoys a higher priority thar <=. Therefore, firct p + I
(17) maino
afld arr+4 arc performed ard then tha <= goes to work. p+i
( yields 6004. wherEas arrH evaluates to 6012, SiDce 60Oa is
int anll={0,1,2,3,4}; less than'6012, the condition is satisfied and fte coIlhol
*p
inl i, ;
reaches pr-intf(-), where value at ( p+i ), i.e. 0 gets printed.
for( p = ar, i = 0 ; p+ i <=ar+4 ; PF[, i+r )
Thed the control r€aches the iacrernentation part of the for
Pdntf ( '96d ', '( P + i) ) ;
loop, wherc p# inq€|trr€dts p to 6006, and ii
inorements I
) to 1. Next, once agaitr the coniditioa is tested. This time p+l
gives 6008 (since p is 6006 and i is I) and arft4 gives 6012.
Output Since the condilioo oDce again gets satisfie4 thi priut(
)
pnnts out the value at ( p+i ), i.e. 2. Similarly, next time
.024 around 4 gefs printed aud then the corditiol fails therefore the
execution is terminated
Explanation
(18) main0
0 I 2 3 4
6004 6006 6008 6010 6012 Output
43210
Figure 2.13
Explanatioh
ln the for loop frcre ee multiple initialisatioDs arld multiple
iroremeDtatrons, each s€parated by the cornma operatol. ln
Chapter 2: Poinlers and Arrq)s t0s
of Output
The following figure would lead to a better understanding
the program. 43210
Explanatio
a'I[0] ar{ll ar[21 arrt3l an[4]
0 I 2 3 4
6010 6012
ar{01 a{tl aEl2l an[3] . a44l
0 I 2 3 4
Pignrc 2.14 The above figule shows the amngement ofthe array elements
in memory-
In the initialisatiotr part, ptr is assiFed the address of the last
element in the array. This is because rrr+4 gives the addrcss In the iiritialisation part ofthe for loop, ptr is assigned a value
ofthe fowth iateger Aom the bas€ ad&€$s. First time tbrough 6012, since arrH gives the addrEss of the fouth integer Aom
the looD the cotrditiotr evaluates to true, siDce the addless of the base address of the array. Here, the variable I is also
the fourtlh elemeot (6012) would certainly be bigger thaD the initialised to 0. Siace th6 condition is satisfied for the first
base addrEss (60M) of the array. Next, the conbol reaches time (i being 0), the printf( ) prints out Ore vatue of ptr[-ll.
prhtf( ), wbi;h prints oltt the value at adiiress cortained in But what is ptrl-il? Nothibg but *( ptr - t ). And since i is 0,
;tr. i.e. \"lue at addr€ss 6012. N€xl, the statement ptr- gets *( ptr - i evaluates to *( 6012 - 0 i.e. 4. Then the control
) ),
executed which reduces pk io 6010. Sirce 6010 is also bigger reaches i+ where i is incr€rnented to l. Nexg the condition is
thar 6004, rhe condition is satisfied onoe again, ard the valu€ checked atrd sirce it evaluafes to true, the prini( ) pritrts out
at 6010 gets printed through the printf( ). This process is the value of pfr[-il. Since this time i is l, ptr[-i] becomes *(
lepeated for all the aray elcments. ptr - I ), i.e. *( 6012 - 1 ), i.e. * ( 6010 ). Thus rhe value 3
gets prinred. Likewise, 2, I ad 0 also get printed subsequent
(1e) main0 times though the for loop.
{
intarll = {0,1,2,3,4 }; (20) main( )
inti,'pf; {
for(pb=ar+4, i =0: i<=4 ; i*) int anlj= {0, 1,2,3,4};
printf ( "t6d ', Pt[-il) ; tptr
int i
)
106 Understanding Pointers In C
Chapter 2: Pointers and Arrqts 107
Explanatiort t
static inta[]= (0, 1,2,3,4 ];
static int'p[] = {a, a + 1, a + 2, a + 3, a + 4l ;
.'ptr : p;
A picture is worth a lhousaDd words. Going by lhis dictum. int
the follolving figure should add clarity to your understanding printf ( "h%u %d", a, 'a ;
)
ofthe pmgram. printf ( 'olou %u 7d', p, 'p, *p
) ;
T.
pintf { ln%u %u %d", ptr, 'ph *ptr ) ;
7888
'Ptr++'
printf ( 1n9{d %d 96d', pr - p, 'p[ - a, 'p[ ) ;
Looking at the figsre, this u'ould turtr out to be 6004 and 0' pdntf ( 1n%d 9(d 9{d!, pr - p, -pr - a,-ptr ) ;
when you execute the p'.ogram' the address may tum out to
++.ptr;
be somethfug other than 6004, but the value at the address
would be surely 0.
pdntf { \%d 96d 9{d', pb - p, 'pr - a, 'pr } ;
)
Now look at the second Pritrtf( ).
Outryt
pdntf ( 1n%u %u 96d', P, 'P,
*P
) ;
111
Here p would give the base address of the aray p[ l, i e' 222
**p
9016; *p would give the value at this address, i.e 6004;
would give the value at the address given by
*p, i.e value at 344
addrcss 6004, which is 0.
Explanation
110 Undentanding Pointers In C Chapter 2: Pointers and Amays 111
Thus tbe ouPul ofthe firsf prhtf( ) becomes II L f ,Ell *-pt',fG7l .@bt"
?888 78BB 6012
Take a deep brealh atd then begin u,ith rhe analysis of
*pt ++. Here * and r+ both are unary operalors.
Since -- Figure 2.18
occurs aller the vadable, + would be dode later. Firstlv
*(9018) is perturmed, but since this value is plr-p
not beini
assigned to any vafable it gets ignored. Next, ++ goes ti
t12 Undersnndirug Pointers In C Chapler 2: Pointers and Arralts 113
Since ptr contains 9020, il can be visualised as ( p + 2 ). Thus *ptr yields 6012 which can be rhought ofas ( a + 4 ). Thus
ptr - p wouldbecome ( p + 2 - p ), which gives 2. the exprcssior is reduced to ( a + 4 - .), which yields 4.
.ptr *ptr
- a
*ptr would give value at addrcss 9020, i.e. 6008, which is *ptr ields 6012, tlEreforc i*ptr would yield the value at
rcthing but the address given by a + 2. Thus ihe expression *ptr, or the value at 6012, which is 4.
becomes (. +2 -. ), which gives 2.
(23) main{)
-ptr
{
*ptr *( 6008 ) static int a[] = { 0, '1, 2, 3,4 };
gives the value at address 9020, i.e. 6008, and +4};
slaticint*pll={a, a + 1, a + 2, a +3, a
gives the value at 6008, i.e. 2.
int'ptr;
I hope youi cortfid€nce is building and you are ready to meet
head on the expressiou *+plr. Here, since +t precedes ptr,
Ptr= P;
i
firsdy ptr is crehented such that it contaios the address HPr++;
9022, and then the value at this address is obtained. Since the pdntf ( \lvd %d 96d', pu - p,
-pr - a, *pr
);
value is not iollected in any variable, it gets ignored. Now .***plr;
having cooked enough pointer stew you can easily imagine printf ( tt%d 16d 96d', pb - p, 'ph - a, "pf ) ;
that the output ofthe third printf( ) woutd be 3 3 3. *"pf ;
printf ( \]%d 96d %d', ph - p, 'pt - a,
*pf
) ;
Finally, let us |mdeistand the exprcssion +*ptr. Here )
obviously, the pdority goes to the r. Thus, this expression
increments the value given by *ptr. Since ptr contains 9022, Olttput
*ptr gives value at 9022, i.e. 6010. This value is incremented
to 6012. So p[3] now contains 6012, whereas value of ptr 1'l
rcmains stationary at 9022- Let us rlow analyse the 22
expressions plr - p, *pli - r and **ptr.
ptr-p Explanation
ptrcontains 9022, therefoE ptr can be imagined as ( p + 3 ).
Thus ( ptr - p ) becomes ( p + 3 - p ), which yields 3. To begin wi&, the anay a[ J is initialised and the aray p[ ] is
set such tllat it contains the addresses of elements of array
'ptr - a r[]. Thus array pl I becomes an array of poitrtels. The base
addrcss ofthis array ofpointers is then assigned to ptr, which
I 14 Understanding Pointers In C
is rightly called a pointer to a pointer The possible of printf( ) is- Let us take otre expressioa at a time and
armngement ofthe aray elemeits in oemory is sho*n in the analyse il slep by careful step-
following figure.
ptr- p
7888 7888
ptr contaiN 90t 8, so *ptr would yield 6fi)6, aod hence **ptr
pts ptr becomes *( 6006 ), which would yield t-
-*..p",1-e018 ptll is
l-;;l | changed
to 6008
Thus the output ofthe first pdntf0 I I l.
tums out to be
7888 7888 .
Since ptr contains 9018, it car be visualised as ( p + I ), thus *ptr gives the value at addrcss 9018, i.e. 6008, and *( 6008 )
ptr - p would beoome ( p + I - p ), whioh would be 1. gives lhe value at 6008, i-€. J.
*ptr would give value at addrcss 9018, i.e. 6008, which is (24) mainO
nothirg but the address given by a + 2. Thus ihe expression (
becomes ( a + 2 - a ), which gives 2. int nl3ll3l= {
2,4,3,
-w 6,8,5,
3,5,1
*ptr gives the value at addrc$s 9018, i,e. 6008, and
*( 6008 )
);
gives the value at 6008, i.e. 2.
f Assume that arEy begins at address 404 '/
Thus the output ofthe secord priu6( ) would be I 2 2. pintf ( 1n%u %u %d', n, n[2], nP]PI) ;
)
Finally, we reach the third expression +**ptr. As the unary
opeElors are evaluated Aom dght to left, the order of Output
evaluation of the above cxpressioa becomes: ( +(
*( *ptr )
*ptr *(
)). since ptr contatus 9018, lelds 6008. 6008 ) 404 416 'l
results i[to 2. This value at the address 6008 is then
incremented ftom 2 to 3. Explakalion
ptr ' p
tr[ ][ ], to begin witlL is declared as a two-dimensional array.
Whenever we mention the name of the array, rie get its base
Siuce ptr coatains 9018, it cm be visualised as ( p + 1 ), thus
ptr - p wouldbecor4e( p + 1 - p ), which wouldbe l. address. Therefore in printf( ), the fiIst output would be the
base address of the array. ln our case it tumed oui to be 404.
'ptr - a
The array elemenls arc aranged in memory as shown in
Figure 2.20. Remembq that thele are no lows and columns in
*ptr would give value at address 9018, i.e. 6008. which is memory.
nothing but the address given by . + 2. Thus lhe expressioD
becomes ( a + 2 - a ), whicb gives 2.
A two-dimensiooal aray is nothing but an array of several
one-dimensional arrays- The 2-D array coltains addresses of
*ptr these l-D arrays. Thus n[0], nul and n[2] contain ihe
addresses 404 410 and 416 respectively. Hen€e the second
output of printf( ). The third output is quite staightforward.
118 Understanding Pointerc In C Chapter 2: Pointers and Anays 119
do]tol 404 406 ,t08 4r0 412 414 416 418 420
nllltol
{21[0]
2 4 3 6 8 5 3 5 Figule 2-21
404 406 408 1tO 4t2 414 416 418 420
n[2] gives tlte base address of the second one-dintensional
array, that is 416. Next comes the expressioa ptu[2]. Can we
Figorc2.2O use such an erpression? Yes, because ultimately ptr[2] is
nothing but r( ptr + 2 ). Thus, even though ph has not been
(25) maino declared as rm aray, we are perfectly justified in using the
( exFessioa ptrJ2l. ptr stores the ad&es$ 404, so *( ptr + 2 )
. int n[3]PI= { " gives the ralue oflhe second iateger from 404, which in this
progam happens to be 3.
2,1,3,
6,8,5,
3, 5, 1
(26) main( )
); {
int'ptr; int nl3ll3l = {
p[= n; 2,4,3,
printr ( \l%u ', n[21] ; 6,8,5,
pdnf ( '%d ', fila ): 3, 5, 'l
printf ('96d', r( fi + 2) ) ; l;
) i,j;
int
for(i=2;i>=0;i-)
Output (
tor(j=2;j>=0;F)
41633 Pdnf ( t|%d 96d', nn[], '( -( n + i) +i ] ) ;
)
Explanation )
Output
ptr has beer declar€d as atr inleger pohter, and to begin v,/irh
is assigned thi: base address ofthe aray, i.e. 404. 11
120 Understa diflg Pointers In C
Anays
Chapter 2: Pointers and l2t
55 414. The value at this addrcss, that is 5, can be obtained
lhrough the expression *( Dlll + 2 ). We know all loo well
that u[1] can also be expressed as r( n + I
88 ). Thus, the
66 expressior *( n[1] + 2 ) is same as *( *( n + 1 + 2 which is
) ),
same as oflll2l. Therefore in general, we can say thar DIilLil
44 rs same as'( *( n + i ) +J
). with that I suppose the outpul of
22 the above program is quitE simple-
(27) main0
Explanation
t
static int a[3][3] = {
Th€ output of n[ilH is as per the expectations, I believe. All 1,2,3,
that is done is, using tlrc for loops, rows and columns are 4, 5, 6,
i j
varied, controllitrg the rcw and coffrclling the column. 7,8,9
what is definitely difficult to oomprehead is the seoond ];
expression in print( ), t*( tr + t ) + J ). Let us try to stalic int 'ptrl3l = { a[0], a[1], a[21] ;
undelslaod ir. The followiog figulo should prove helptul in inl "ptr1 = ptr i
doing so. inti;
printf (\" );
for(i=0;i<=2;i++)
pintf ( 'ol"d tprU
2 4 3 6 8 5 3 5 1 ", );
404 406 408 4tO 412 414 416 4t8 420
pdntf("\n");
for(i=0;i<=2;i++)
pdntf('%d ', tafl ];
Fignre2.22
'b') :
pdntf (
kflagine a 2-D array as a collection ofseveral l-D arrays. The for(i=0ji<=2;i++)
only thiog that the compiler needs to rememb$ about a 1-D {
array is its base address. Thus, if Oree l-D arrays ar€ to be printf ( 'yod ', *ptrt
);
remembere4 the compiler should store somewh€re the base Ptrl++'
addresses of these armys. These base addresses are stored in )
n[0], nlll aod n[2]- Now ifn[l] gives the base address ofthe )
first array, lhen n[l] + 2 would give tlre address ofthe second
itrteger from this base address. In this case it tums out to be Output
122 Unilersnnding Pointers In C Chapter 2: Pointers aad Anays 123
r- {
1,6,2,4,
0, 7, 9, 5
Figue 2.23 )
oontaining the );
ptr[ ] has treen declared as alr array ofpointeN .( -(.(
tasi'addresses of the tluee l-D arrays as shown in Figure
.) printr ( "\n%d %d',
{21[1181, r+2)+1)+3))j
2.23. Orce past tbe declaratiotrs, the control rcaohes the first
for loop. tn this loop tlrc pritrtf( ) pfirts the values at Output
addressis storcd in ptrtol, Ptrtfl and ptr[2], which tum out
to be 1, 4 and 7. 55
III rhe trext for'loop, the values at base ad&esses stored in the
Explanation
anay a[ ] are printed, which once again tum out to be 1, 4 and
7. The third for toop is also siinple.
In memory the 3-D array elemeots are arranged as shown m
Since ptrl has been initialised to the base address of the
array
*ptrl Figwe 2-24.
otrl l. it coolains the address S22 Therelore would
;iv; i; value at addrcss 822, i.e. 'l(}4' and **ptrl would give
ihe value at address srven by
*ptrl' i e value at 404' which is
124 Understanding Pointers In C Chapler 2: Pointers and Arrays 125
Explanation
2436 1679 82ll 217f 1624 0'7 9 5
Yes
200 204 2t6 224 212 240
{D For.th€ statements in(l) does the compiler letgljLe character
. arrl3l and ptrl3l in lhe same mannerz
Figtre 2.24
Explahatio
Here t[ ]l l[ I has be€n declared as a tbree-dimensional array
A 3-D alray can be considercd as a collection ofa number of
2-D arays- Thus, the first expression in the priotf( ). - generates code to stan at locanon
No. For arr[3] the compiler
t[2llt][]l refers to the elernent in l" row. 3'o column ol the 2n0 arr, move thrce past it, and fetch the character therc. When it
2-D array. This tums out to b€ 5, vt/hich is printed through sees the expiession ptr[3] it gercrates the code to start at
pritrtf( ). locatioD stored ill ptr, add three to the pointer, and finally
felch the character poinled to.
The next exprcssion in printf( ) is a little complicated. Since
the only thiflg that the compiler needs to remember about the ln other words, arr[3] is tkee places past the start of the
thiee 2-D arays is their base addrcsses, dlese addrcsses are object named arr, whereas ptr[3] is three places past the
st6rcd h r[0], t[1] and t[21. Therefore, the expression t[2lu] object pointed to by ptr.
would give ihe address of the first tox, of the second 2-D
array. Referring to the figue, this address turns out to be 240. (3) Can you comlrine the following two statemelts into one?
To this address if we add 3, we would get the address of the char 'p ;
third integer from this address. This address would be 246. p = malloc (100 );
Naturally, the yalue al this address (i.e. 5) can be obtained
through the expression *( tl2l[1] + 3 ). But t[2][1] itself can bqlanatioh
be expressed as *( t[2] + 1 ). And in this expression t[2] can
be exprcssed as *( t + 2 ). Thus the expression *( t[2]Ul + 3 ) char.p=rp211o.11*,
can be expressed as r('( *( t+2 ) + 1 ) + 3 ).
/4) Does menrioning lhe array name gives lhe base address in all
[Bl Answer the follorving: / ihe contexls?
{1) For the follorting statements would arr[3] and ptrl3l fetch
Explanation
the sahe cha€cter? <YeVNo>:
- When array name is used with sizeof operator. No, because we 1rlay assign a new string to a Pointer but not
- Whea the array aame is al operand ofthe & operator. to an aray.
(5) Arc the exprcssions arr aod &arr same for an arrav of 10 r]
(8) A pointq to a block of memory is effeaively same as an
integers? array. <TruelFalse>
Explanation Explanatioa
No- Even though both may give the same addiesses they mean True
two dillerent things. arr gives the address of the first int,
whereas &arr gives the address of array of itrts. Sioce these (9) What does the following declaralion lnean:
addresses happen to be same the results ofthe expressions are
same. int (.ptr)f0l;
(p)
n When char aJ I aDd ch.r *a are treated as same by lhe Explanalion
compiler?
ptr is a pointer to an array of l0 integers.
Explatation
(I 0) If we pass the name of a l-D int array to a function it decays
When usirg them as formal pammeters while defining into a pointer to an itrt. lf we pass the name ofa 2-D array of
a
function. integen to a function what would it decay itrto?
Explanation
'(r(*('(a+i)+j)+k)+l)
( I3l ln the follo\i ing program how would you prinr 50 using p?
main0
{
int a[]= { 10, m,30,40,50 };
char'P;
p=(ch . )a;
)
Ettplatatioa
int anl[rAXROlfl][MAXCOL] ;
fun ( ar);
Explana/io
(1) main{)
printf (t') ;
for ( i= 0; i<= 8; i++ )
{ (
int anl3l[3]Bl ;
pnnf ( '96d ', 'pt2 ) ;
Pt2++;
f Assume base address of ar to be '1000 '/
)
pdntf ( \l%u %u %u', ar, at + 1,ar+2\:
pintf ( '\n%u you %u', anlol, an[0.] + 1 , arfl ) ;
prin$ ( 'Vr') ;
pintf('h%u %u %u', adllt11, an[1][0]+ 1, an[0][1] ) ;
for(i=0;i<=2:i++)
] prinr ( %d ', -( pldll ));
3,4,
Ihe likelihootl 4d program crashing is in direct ptoportio\ to the
5,6
txmber ofpointers used ii it-
),
{
3,4,
1,2,
5,6
),
{
5, 6,
3,4,
1,2
); Qointffs dnlstr@s
pintf { 1n96d %d '('(
9{d ',
.(.(.(a+2)+ ]a[0] + 2
), + 1
1 ) + 1 ),'(anl[4+ I )) ;
(5) main0
{
a[]= { 0, 1,2, 3,4 };
static int
staticint*pll = {a, a + 2, a + 1, a +4, a +3 } ;
int -plr ;
n the last chapter you leamt how to define arrays of differing
sizes aad dimensions, how to initialise them, how to pass them
ph=p; to a functiols, etc. With this tnowledge under your belt, you
*.++ptr; should be Eady to hatrdle s&iags, whioh are, simpty put, a special
kind of aray. String$, rhe ways to htuipulate them, and how
printf ( "h96d %d %d ', 'plr, plr - p, 'ptr - a ) ; poi ers arc relaied to strings ale going to be the topics of
discussion ill this chapter.
character arrays, but somehow conceal this fact from the char namel] = 'HAESLER' ;
programrner. Character am5rs or strings are the data types used by
Fogrammlng languages to manipulate text such as words and Nole !hat. in this declaration'\0' is not necessarv- C inserrs rhe
sentences. null alrromatically. Ih€ \0;;;;l md,-m irinttng strings.
This is illustrated in the follovring pmgram.
A string coDstant is a onedimensiooal array of chgllcters
tenraffi truf f $uTJ;iexamfi i /- Program 33
*/
main0
char namel] = ('H', A,'E, 'S,'lJ,'E,'R;10 ]; {
char namel]= "Kilnsman' '
Each chaBcter i4ihc alrallqccupieq@bdE-qf$!9oq lnd_ge int ij
last character is always '\0'. Whal charactq is this? It looks like
two charaitec,-Tutliisi6rally atr escape sequenoe like 'h', It is i=0;
called 'null character'. Note @t'\o: ad '0: q,e'!pt s4-m9. ASCII while ( oamen )
value of '\0.Js O, whereas ASCtr value 9f '0' is {!. The charaoter (
anay iriffi'ry would look lfte this: printf ( 'bo/oc yoc yoc %d, name0,
' ( narE + i
.(i+name),ilftaneJ]; ),
i++;
)
H E s L E R \0 )
KKKK
Figue 3.1 t t
iiii
Note that the array elemeots arc stored in coEhguous memory nnnn
locations. ssss
mmmnl
The terminating n! l ('\0'l is importatrt, because itjsjhlonulvay aaaa
rhg fiuctiaDs that work with sEing can how where-altringinds. nnnn
In fact, a string not telffifre6d by L:\0:is not really a strin-g. but
mer$-Lsollectiod of characteN. This program doesa't rely on the length of the striag (number of
characters in string) to prinl out its co ents and hence is definitely
C concedes rhe fact that you would use strings very often and more general. Here is aaothea version of the same program; this
hence provides a shortcut for initialising strings. For example, the olre uses pointels to access the aray elements.
string initialised above can also be initialised as,
136 ChLpter 3: Pointers and Strings 137
The turctiotr xstrle( ) is fairly sirrple. All that it does is it keeps final string. I lsave it to you to develop your own *sttcat() an
counting the chaiacteN till the eod ofstring is trot met. Or in other hnes of xstrlen( ) ard xst{cpy( ).
words keeps counting-gbaracters till the pointer s doesn't point to
Another useful striag fuootioo is strcmp( ) which compates two
strings to find oulltrtrcfhelthey axe same or differetrt. The two
Alothcr function that we have used in Program 37 is strcpy( ). strings are compared lette. by letter until there is a mismatch or
This functiol oopies the contenls of one strilg into another, The end oFonsolltre sdqg! i! iqcheq whichever occurs first. If Ore
base addresses ofthe source and target stdngs should be supplied two strings are identical, strcEp( ) reh'rtrs a value zero.'lf thev're
to this tunotion. On supplying the base addElgggsEgylLljoes not.li r66mllEE nunreric differenie betw:en th-the ASCII values of
on copyiDg the source shitrgjllq lhp target striDg till it doesn't Lhe first nonl-nratciinlitir of characiefs.
encounlEilfiEdod of source strirg..ll is our .espo;sibility to see to
it that target string's dimeasion is big enough.Jo hold-the string The exact value of mismatch will mrely concem us. All we usually
beine,aopiedjaro it. Thuq a string gets copi€d hto aoother, piece- want to know is vhether or not the first string is alphabetically
meal, charaoter by oharacter. There is no shortcut for this, Let us above the second string. If it is, a negative value is returned; if it
now ancmpl to mimic strcpy( ) via our own st ng copy firnclion. isn't. a posirive value is refumed. ADy non-zero value means there
which we lvouldca rstrcpy( ). is a mismatch- ter us try to implement this procedure into a
function xstrcmp( ), which works simitar to the strcmp( )
xstrcpy (char1, char's ) function.
{
while (.s l= \0') xstrcmp ( char 's'1 , char's2 )
( {
,t ts1
=.s; while ( =='s2 )
s++; (
l++; ir (
.sl
== 10' )
I Ietum (0 ) ;
't = \0' ;
) sl++;
s2++ j
Note that having copied the entire souce string irto the target .)
it rj necgssSry_bglac: a '\0' into the larget string to 44rk
:trinCt
trs end. retum('s1-'s2);
)
The strcat( ) furction concateDates the source string al the end of
the target string. For exarnple, "Bamboozled" and "Chap" on
concatenation would result into a strilg "Bamboozledchap". Note
that the target shing strl I I has beetr made big enough to hold the
142 Understanding Pointers In C Chapter 3: Pointers and Strings 143
fProgram 39 '/ const qualifier ensures thar your program does not inadvertently
main( ) alter a variable that you intended to be a constant- It also reminds
{ aflybody rcading the program listing that the variable is not
char strl []= "Hello' ; intended to cha[ge. Variables wih rhis qualifier arc often named
charstu2l10l;
in all uppercase, as a reminder that they are constants. The
following program shows the usage ofconst
char.s = 'Good Momir€' ;
char'q i
f Program 41 '/
main0
sf2 = std jf enor*/
(
q=s;/'works./
float r, a ;
) const foat Pl= 3.14:
Alsq. o-!.ce a sqiqe laq tregn defned. pdntf ( lnEnter radius: ');
strings, such an operation is scanl ( 'olof, &r ) ;
a= Pl'r'r;
/. Program 40 '/ printl ( "Area of circle = %f, a ) ;
main0
)
{
char strl [] = 'Hello" '
char'p = 'Hello''
144 Understaading Pointen In C Chapter 3: Pointer: and Strinss 145
This progmm simply copies the contents of sfrl[ I into str2l ] t = 'Bye' i f ercr'/
using the firDction xsarcpy( )- What would happen if we add the */
following lines beyond the last stat€ment ofxstrcpy( )?
constchar*constu='Helb-;f*iU b consbnt so is trinter
'u='M;fenor'/ */
s=s-6i u='8ye';ferDr
r46 Undersnnding Pointers In C Chapter 3: Pointers and Strings 147
Returning consl Values a program. Our example program asks you to qpe yout name.
Wllen you do so, it checks your Dame against a master list to see if
A function can return a pointer to a conshdt stritrg as shown you are urofihy ofentry to the palaoe. Here's the progmm...
below.
f Program 44
*/
I #include <stdng.h>
Program 43 '/
#define FOT ND I
main0
#define NoTFOUND 0
t .tun( main( )
const char );
consi char 'p ;
{
char masbrlistlolllol = {
p=tunO; 'afStay'''
.P ,paras',
= enor'/
'A' ; /.
printf("\n%s",p); 'ftman',
'sinivas',
)
taar,
const char ' tun( ) 'rajesh'
{ ):
int i, iag, a;
retum 'Rain' ;
charyoumamenol;
)
And herc is the output fot two sample runs ofthis proglam...
akshay\o parag\o gopal\o rajesh\o
Enter your name: dinesh
Sorry, you are a bespasser 1001 1011 t02t r03l 1041 l05l
Notice how the twoiimensional cha@cter aEay has been Here, 1001, l0l l, 1021, etc. are lhe bqqi3ddresses of successive
initialised. The order of the subscriDts in tle a namds.Es-E6-E6--iEe above 6gure, some of the names do not
impoltant. The first subscript givas thinumber of names in the occupy alllf,66-yes reserved for them. For example, even though
array, while the second subscript gives the length of each item in 10 bltes arc rcseryed foi storing the name "akshay", it oocupies
the array. only 7 bytes. Thus, 3 bytes go waste. Siinilarly, for each namc
there is some amount of wastage. Itr fact, more the dumber of
Instead ofinitialising names, had these names been supplied from names, more would be flle wastage. Cao this not be a\oided? Yes,
the keyboar4 the program segnent u,ould look tike this... it can be... by usiog a data tlTe caled atr array of poiltsrs to
strings. whicb is our oext topic ofdiscussiotr.
for(i=0;i<=5;i++)
scanf ( 'Yos'. &masbrlis{ilpl ) ;
Another reasotr to use alralglpqiq@-to" sl9le.-s$TgLi-s:l;o_guhin fhus, from the point ollgglStrg.igrt-EE r"ry usage and ease
greater earie in tte manipulation of the stsiggs. The following of programming, an arFy of pointers to strings definitely scores
prcgra@ isverysimple. over a two-dimeflsional chaiacter array. Tbat is wh. y, even though
We watrt to exchange the positions of the names "Ianrad" and in principle sFings can be $lorcd and handled throl:g} a two-
"$inivas".
Chapler 3: Pointers atd Strings 153
152 Undentanding Pointers In C
for(i=0;i<=5;i++)
dimensional ar-.ry ofcharacters, in achral practice it is the aray of {
i
pohtels to strilgs which !trorq corEnoDly used. pdntf(\Enternane:!);
scanf ( '%$. namesE ) ;
In Plogram 45 iastead of o@hangiry the within main( )
oames
)
suppose we d€cide to carrJ. out this crchadge through a furBtion )
Bwap( ). To this futrction suppose we would pass the addresses
givel by ( tramer + 2 ) and ( nrmca + 3 ). These addr€sses would Tte progmm doesn't work because when we are declaring the
be collected ir two vadables, which are pointers to pointers aryfj-s.-coltabiryj Jdues, Atr?im;ia-G;;E;tety
(why?). Using these pointeN theri the Dames can be exohanged. wrong to sefld these galbg ( ) as the addresses
This is how the $wap( ) fimction would look like... where it should keep tf,e strings received from the keyboard.
su/ap ( char
*sl, char \2 ) As a compromise solutiotr we may fiIst allocate space for each
( name using malloc( ) and then storc lhe address rehrmed by
-char't; /. malloc( ) in the aray of pointers to shitrgs. This is shown irt the'
following program-
t = 's'1 ;
's1
.s2
= 's2 ; f Program 47 '/
= l; f Program to overcome limihthn of aray gl pointeE to stings '/
) #include <alloc.h>
#include <shng,h>
Limitation of Array of Pointers to Strings main0
{
char 'name[s] ;
When we are using a twodimtglqi@!
libefiy to eithet idtiali lhe saings where we are <GEl'riry the char str[20] ;
int i;
array, or teceive the stings using $crD( ) fi{rotion. Howeve!,
when we are using an array ofpointers to strings we can idtialise
for(i=0;i<5;i++)
the strings at rhe p.laoe whc(e we aI€ declari[g tte aray, but we
{
cantrot receive the stings fiom kE/toad using rcenf( ). Thus, the '
Pdnf (lEntera Stim' ' )
following pogrm would rcver wort out. gets (slr);
nameu = ( char') malloc ( stlen ( ifr) );
f Program 46 '/ stnpy(naflEfl,dI];
main( )
)
{ for(i=0;i<5:i++)
char'nsmes[6]; printl ( 1n%s', nameE ) ;
154 Uiilerstand@.Pointers In C 155
mile
Solved Problems
Explanation
[A] What will be the output of the followiug progmms:
When we pass a stiag to a function, wbat gets passed is the
(1) #include <sting.h>
base address ofthc string. Itr this case what is bsiog passed to
main( )
prht( ) is the base address plus 5, i.e. address of 'm' in
{
char s[ I = 'Rendez\ot6 !' ; "faosimile". prlntf( ) p.ints a string startiug from *re address
prinf ( 1n%d:,' ( s + sthn ( s ) ) ;
it receives, up to the etrd ofthe string. Hstroe, in this case
)
'mil€' gets printed.
(3) maino
O"tPut
{
char ci[20] ;
0
inti;
tor(i=0;i<19;l+i)
EJepla ation '(ch+i)=67'
'(dr+i)=10''
prinf ( t96s', ch ) ;
No 'Reodezvous !', but a zero is printed out. Mentioning the
name of the string gives the base addrss of the string. The )
tunction strlen( sJ itums the length of the stling s[ l, which
in this case is lz-In printf( ), usiag the 'ralue at address' O rput
operaror (often called 'contetrts of operator), we are trying to
print out the contents ofthe 126 addrcss Aoul the base address ccccccccccccccccccc
of the strlag. At lhis ad&ess there is a '\0', which is
automatically stored to mark the eod ofthe striag. The ASCU Explatation
value of '\0' is 0, which is what is being prioted by the
prtntf( ). Mentionilg the rume of the array always gives its base
ad&e$s. Thercfore ( ch + i ) would giv€ rhe add&ss of the i6
(2) main0
elemetrt from tbe bos€ ad&ess, aod *( ch + I ) would give the
{ value at this address, i.e. the value ofthe i6 elernent. Tlfough
pdntl (5 +'Fffiinile );
lhe for loop we storc 67, vhich is the ASCtr value of upper
)
case 'C', in all lhe locations of the string. Once the codrol
reaches outside the for loop the valuc ofl would be 19, and in
Output
the l9d location froE lt€ bas€ address we storc a '\0' to ma*
the end ofthe sting This ir essential, ac Oe compiler has no
1s6 Unilerstanding Pointers In C Chapter 3: Pointers and Strings
other way of knowing where the shing is teminated. Io the cordition evaluates to tue every time. IEespective ofwhether
pritrtf( ) that follows, 7.s is the foIEBt specifioation for the condition is satisfi€d or trot r is itrcrgmented so that each
printiry a stting ad c\qives th. b"leaddress of the string. time it points to the subsequcnt aray elemed. This entire
Hencc*artitg ffinr the first eleme , the complete string is logic is repeated in the for loop, printing out l0 zeros in the
prhted out. - process.
Output Explsnation
000000 0000
/ When we meotiou the oame of the ariay we get its base
address. Since strl and str2 are two different arrays, their
Explanatiott
base addrcsses would alwalas be differetrt. Heflce, the
couditioa in if is awir goiDg to get sati$fied. If we are to
In all 10 elem€nts of sh[ l, ar integer, 48 is stored. comparc the conte s of two chrr atays, we should compare
Wooderhg whether a char string cao hold itrts? The answe! them on a character by char.cter basis or use strcmp( ).
is yes; as 48 doe! not g€t stor€d literally iD the clernelrts. 48 is
iuterpret€d as lhe ASCI value of the ohalactel to be stored in (6) maino
th€ string. The charact€r cotespotding to ASCII 48 happeN {
,o be 0, which is assigned to all the loc.tions of the string. charst4lol = { 0, 0, 0, 0, 0, 0, 0, 0;0, 0 } ;
char's ;
e, a characterpohter, is assigaed the base ad<hess ofthe stdng inti;
rtrH; Next, in the if conditio4 the value at addr€ss contahed s=str;
io r is chect€d for tuth/hlsity. As 0 lepresellts ASCtr 48, the for(i=0;i<=9:i++)
1s8 Understanding Pointers In C Chapler 3: Pointers atd Strings 159
if
-s
{ )
pdntf ( '%c', -s ) ;
s++; Explatatiott
The above program nrbs irl the point Olat s[il, i[sl, *( s + i )
Olttpul
and *( i + s ) are various ways of referring to *re same
element, that is the ib elemc[t ofthe stsiDg !. Each element of
122
the stritrg is pinted out four times, till rhe en<l of the string is
encountered. Note that in the for loop therc is al1 expression
Erplanatioa s[i] in the condition pat. This meaas tte loop would continue
to get executed till s[il is rot equal to zero. We oan afford to
Me[tionhg the name of the array gives its base addrcs$. say this because a string alwaSrs ends with a '\0', whose
However, wheu used wilh siz€of( ) it yields the number of ASCII value is 0. Thus the for loop will be teminated when
bltes occupied by the array in mernory. Since str is holding the expression s[tl yields a '\0'.
six addresses, of2 byt€s eacll $lzeof( str ) gives 12.
(11) main( )
str[0] yielils addrcss of "Frogs'. this ad&ess is reported as 2 {
bytes big. char s[! = 'Oinks Grunb and Gutrav6' ;
pdntf ( \96c', '( &s[2] ) ] :
(10) main0 printt(tu9k',s+5);
{
pdntf(tryos',s);
char s[] ='C smad' ' printf ( \Yoc','( s + 2 ) ) ;
inli; printf(\%u',s);
for(i=0;sn;i++) )
pdntf ( 1n%c %c 9dc %C, sn,'( s+ i) , ilsl,'( i+ s)) ;
) Output
Output n
Grunts and Gutrau6
cccc Oinks Grunts and Guffa,,!,s
ssss n
mmmm 404
aaaa E4
rrrr anation
tttt
!!t! In tlie fiIst printf( ) the 'address of operator, &, gives the
address of the secotrd element of the string. Value at this
Explanation address is 'a', which is printed ollt by the printf( ) usirg yoc.
Output
Explarratio
'ple@'
);
srt
staicchar-MI={s+3,s+2,s+'l,s};
1
char-p = pg '
I- k \0 pdntf('ln%s',*+ip);
4001 4002 4003 4004 4005 ,1006 4007 4008 4009 4010
Printf ( tli6s','-'+lP r 3) ; -/
prinf(t96s"'pt-4+3);
pintf ( 1no/Gs', p[-llF1l + 1];
)
cone
p point to the oext locatioo of its type. The words 'of its q?e'
would decidedly aid you to get disentangled. Thus, is
hold significance here. A pointer to a char on incrementing
assigned lhe addrcss 6020.
goes ooe bj.te fifther, sirce a .htr is a l-byte entity A
pointer to arl iBt points 2 byt€s fi ter, as an irt is a 2-b]te
entity. Also, a pointer by itsef is always a 2-byte entity, so
increm€lting a pointel to a poiok would .dvanoe yoo by 2
\olslilele \o nle I\01 DI 1 3 \0
bltes.
1000 1004
Having convinced ourselve$ thtt P trow storcs 6022, we go on
to evaluad:'the exprcssion firther. rp signifies contents of
stol 6022, i,,e, 4ol0. r'p meaDs vatue at ltis add!€ss, i.e.' value at
4010, which is the address lOlO- The prlrrtf( ) p nts the
,rol0 4012
string at this address, which is 'cone"-
r-r++p + 3
pl-1llll+ 1
"rt l
The sbove €4,r€ssion oao be thought ofas *( pl-U - f ) + f,
F I I I v
ar num[il aod r( n[D + ) amounts to the same thing. v v s ,0
i
Further, p[-11 can itselfbe sirrplified to *( p - I ). Hence we 4001
can interyEt thc given expr€ssiotr as *( *( p - ) - 1 ) + f .
i
Now lel us evaluate this exprcssion. p
AAer the execution of the third printf( ), p still holds the l-;or I
address 6024. *( 6O14 - f ) gives r( 6022 ), i.e. address 4010.
Therefore the erpt€ssioo Dow becomes *( 4010 - I ) + 1.
Figue 3.6
Looking at lhe figore-you would agree tllat 4010 can be
expressed as r + 2. So now the expressior becomes *( s + 2 - The for loop here hosts two initialisations and two
1 ) + 1 or *( s + I ) + l. Once again the figure would confirm incrcmentations, which is perfectly acceptable. However,
that *( $ + 1 ) eialuates to '( 4008 ) and *( 4008 ) yields 1004, there must alli.ays t e a unique test conditio[
which is the b6se addrcss of the second string "green". To
this, I is addid to yield the address of the first elemert, 'r'. In the initialisation part, p is assigned thg base address of the
With this as the startitrg addEss, prhtf( ) prints out what is string, and i is set to 0. Next the conditio[ is tested. Let us
rcmainitrg ofthc string "green". isolate this condirion lor closer examination.
p + 1<= sf + stlen (st) This way ooe by olq the elements ofthe sEing are printed out
4019 <= 4019
in the reverse order, till s equals str, the addrss ofthe zeroth
element. That the output is indeed the reverse ofthe original
The l8d el€usnt of ttr
is of coulse the '\0', whioh is also
string can b€ verificd if you read 'MalayalaM' backwar&.
pritrted out as a blalt- Otr filtther inctemeotation of p and i.
You have bcen presented with a suing ttat reads the salne
iootrol snaps out of the for and the program execution is ftom eithff end. Such strings, inoideotalll go by the oame
terminatetl
'Palirdrcme'.
(16) main0
(17) main0
t
, char stll = xldaydr ; {
'
char al I = 'Able f,as I ete I saf, elbA'
char's; *s,
s=sf+g; char1,'b;
while ( s >= sfr )
s=8;
(
b=a+sHen(a)-1;
pnnf{'9{c',t); t=b;
while (s != I )
s-: (
) pnnf('96c',t):
) s+;
pdnif( ',1);
Output t-;
)
MahyalaM
)
Explanatioa' Output
C is a philosophy ol lih
The char pointer r is assigned the base ad&ess of seing a[' I.
The ch.r pointgr b is assigned the addrcss 24 elements ahead ErplanarioL
of the base address. Why 24? Because the furction sHen(a)
yields tlle length ofthe string a[ lr which itr this case tums out To begir with, ss and tt are assigned the base addresses of the
to be 25. Thus b points to 'A'presed at the end ofthe string. two strings sI J and t[ l. In the while, the value at address
Another character pointer, t, is also initialised to the same contained in ss is tested for operating the loop. The first nme
value as b. Assuming the base address of the st irrg to be through the loop ss contains the base address of the string.
5001, s would be assigned 5001 atld b and t would be Hence *ss gives'C', whose ASCII value is 67. As any [on-
assigned the address 5025. zero value is a t[uth value, the condition evaluates to tue, and
this valuo is stored at the addiess contaircd in tt, i.e. at the
Natuelly, first time thrcugh the while loop sioce s and t ee base addrcss of the stritrg t[ ]. Note that the opentor+
not €qual, the condition is satisfied. Hence the Pdntf( ) priats
occurs afier the variables, so aller 'C' has been stored in the
out the chamcter at which s is pointing. Thus the character 'A'
first location ofthe string t[ ], both ss and tt are incrcme[ted,
gets printed. Now s is inoremented, so that it poirts to the
so olat both now point to the fiIst elements of s[ ] and t[ ]
character 'b'. The next printf( ) prints the value at ihe addrcss
respectively. In the second go, value at the addrcss contained
oontained in t. Thereforc another 'A' appears on the scleen.
in $r is tested in the while, and this time a blank is
Affer printing, t is defiemented so that it starts pointing to 'b' .
encourterc4 whose ASCII value is 32. The condition again
This goes on till s ard I meet each othir, whence the while
'/, holds good, therefore the blank is storcd in string t[ ], and ss
ends. At this instanoe, 3 and t both arc pointing to ihe
and tt arc incrernented. This goes on till the end ofthe string
middle charaqter oflhe entilo string.
is encourtered, At the end of any string, a '\0' is stored.
(18) maino
ASCII value of'\0' is 0, which when tested in,the while,
evaluates to fi[sity, and the contol comes out ofthe loop.
{
char sl I = "C is a philosophy of life' ;
Note that the '\0' has not been stored into string t[ l.
hence the
char t[40] ;
*ss, compiler does not larow where the string erds. We do so by
char 'tt :
insertiDg a '\0' on leaving the while. Finally, the contents of
t=t; lhe stsing t[ | are pdnted out.
while ( 'ss )
rss++ (1e) rnE in( )
1t++ = i
't=\0'; {
printf(\r%s",t); dlarsll= 'Lumps, bumps, srrcllen veins, rEw pains':
)
dffltr4ol;
dlarts,'t;
Outplt
t=t;
ss=s;
174 Understanding Pointers In C 17.5
-tt++
while ( =.ss++ ) i false since *tt yields a 0 (ASCII value of '\0'). Thus, all
pdntf("\nYos',t);
elements of the first string are faithfully oopied into the
) s€cord one, including the '\0'. On printing out sfting tl l, we
get the entire string as it was in 3l l,
Output
(zo) maini )
Lumps, bumN, su/ollen veins, newpains
{
int ad12l i
Expldnation pdntf ( \l%d', sizeof(ar) ) :
)
The program begirls by assigniag the ba8e addtesses of shings
s[ ] and t[ | to th€ chaBcter poitrte$ !s and tt. The whlle loop Output
that follows next may raise a few eyebrcws. We have made it
24
oompact by combining the assigntnent, test conditio[ and the
inorcrnentation in the whlle loop itself. In effect the whlle has
been reduced to: Explanarion
rss++
whlle ('tt++ = ) The slz€o( ) opsrator givcs the size ofits argument. As arr[ ]
is an integer array of 12 elsments, saying rlzeof ( 8rr ) giveE
us the size of this aray. Each integer is 2 byt€s long, hsoa€
Hele the Ilull statement is executed so long as the condition the array arrl I eogages twioe the numbe! of elements, i.e. 24
remairN true. How the condition is €valuated is like this... bytes.
In the while the value at the address storcd in ss replaces the (21) main( )
value at the bddrcss stored in tt. After assigoment the test is
{
carried out io decide whether the while loop should contirue
or not. This is done by testhg the expression rtt for
char'rnensl l = i
"Some love one',
truth/falsity. Since curently tt is pointing to 'l' of'lumps', .tt 'some love two',
gives '1' which is a truth-value. Following this s3 aird tt both 'llo,ie one',
are inqemetrted, so that they have the addresses ofthe fiIst ' 'That b You'
elements of strings s[ ] and t[ ] respectively. Siooe the );
condilion has been satisfied the null statement is executed. pdntf ( t96d %d', sizeof ( mess ), sizeof ( mess I1l ) ) ;
82
ENTER NAME: Veenu
You enteed Veenu
Explanation ENTER NAME: Jaina
You enbred Jaina
messl J has been declared as an array of pointers to striogs.
This signilies that the array messl ] stores the starting Erplanation
addresses of the four strings initialiied in the program.
mers[0] has the sta ing addess of the string "Some love
namer[3][20] has been declarpd as a two-dimensional array
one", messll] the starting addrcss of the second shing',Some
of characters. We can think of it as an array of 3 elements,
love two" and so on. As each address is 2 bytes long, four
each element-itselfbeing an array of 20 charaoteN,
base addresses need 8 bytes, herce thc array messl I is 8 bytes
long, Let the base address of the 2-D alray, i.e. names be 400 I . In
the scsnf( ) and pritrtf( ) statements, !smer[] refers to the
The sizeof( ) operator gives the size of the datatype that is
address of the I'h string in the aray. mmeslol refers to the
supplied as its argument. Thflpfore, sizeof ( mes3 ) is rcported
zeroth element of the 2-D array, or the base address of the
a8 8.
string ofcharacters Etarting from 4001. llrmesll] deflotes the
address of the fiIst element ofth€ 2-D artay, which is 20 bytes
mess[l], the filst element of the array of pointers storcs an
ahead, i.€.4021, and so on.
addreBs, whioh is invariably 2 byte6 long. Thereforeprirtf( )
reports slzeof( me$lll ) as 2.
Assued that trrm€slil stands for the base address of the I'h
(22) main0
shing, we ploceed to see what actually is going on in this
program.
(
char names[3][20] ;
The fiIst time though the for loop, when you arc prompted
inti;
for(i=0;i<=2;i++) "ENTER NAME:", say you entered 'Parag'. The scanf( )
accepts this name and stores it at the address given by
t namesl0l. The priDtf( ) iflmediately reads Aom lhe same
pdntf ('\nENTER MIrrE:' ) ;
scanf ( '%s', narnesm ) ; address name[0], and pdnts the rEme starting at this address
printf ( 'You entercd 96s', namesli] ) ; on to the screen. This is repeated by incrernenting the value of
) i each time through the loop. Who i is incrcmerted for the
) third time. thc process is lerminated.
the aday. The same array element can thus be accessed in any
of these three ways. The pritrtf( ) on execution outpnts the (3) In the followi4g code which function would get called, the
letter 'k' twioe. user-defined strcpy( ) or the one in the standard library?
#include <sting.h>
IB] Answer the folloving: main0
(1) Is the following pogram colrect? <Yes,No> t
char strl[]= 'Keep India Beauliful... emigratel" i
charsl2[40]j
main0
slrcpy ( sl4, strl ) ;
t prinf('\n%s", st, )i
char*slr1 = 'United';
char
*str2
"Fmnt'i
)
=
char'str3 i
sircpy ( char't, char's )
str3 = strcat (str1, str2 ) ;
p {
ntf ('\n%s', str3 )i while ( 's )
)
{
Explanation t++;
)
A 8thg car bc proc€8sed ody o! 8
(6) Would the foltowing code oompilc sucoessfully? basis.
maln( )
{
printf ('%c', 7l'Sundaram" I ) ;
Explanaliofl
ch8r*p = 'Sanuel" ;
charall= "Samuel' ;
Etqlaaation
Here a is all aray big enough to hold the message aod the '\0'
following the message. Individual charaotgrs *ithio the array
184 Understanding Pointers Jn C , 185
The funotion should retum a pointet to the elemert in strltrgl IBI What will be the output ofthe following programs:
where strlng2 begins. IfltrlEg2 doesn't occur in stritrgl lhen
xstrstr( ) should rEhrm a NULL. (1) main( )
{
For example, ifetrlngl is nsomewhcre over fte rainbow", and char stingl J = 'oddLengfiStting' '
.trltrg2 is "over" then rrtrst( ) should retum address of 'o' char'ptr1 = sfing, 'pM = sting + sizeof (string
)- 1.
in rtrlDgl, inti:
(3) Suppose 7 names are siorEd in an aray of pointers mmer[ | for(i=0;ptrl l= pf2;i* )
as shown below: {
++ptrl ;
char 'names[ ] = (
-N2;
'Sanbsh', )
'Amol', pdnf( '%d', i) ;
'Sanh6h Jah',
'KhlDe-,
)
'Rahuf, (2) main( )
'Amollumai,
{
'Hemanf shtic char slrl [ ] = 'Good' ;
);
Chapter 3: Poi ters and Strings 187
.ss
while ( ll 'lt )
t
while ( 'ss )
{
if( ('uu++ ='ss++ 1 == " ;
bBak;
)
An e4)erl C Programtuel is o e who avoids all elrols except those
relaled with poi ters.
IProgram 48 '/
main( )
{
struct munt
190 Understanding Pointers In C Chapter 4: Pointers and Straclures 191
int no i
char acc_namel15] ;
lioat bal i al.no a1,acc name al.bal
); 375 lsameer\0 11234.55
struct account a1, a2, a3 i
.,l00l 4003 4018
printf ( "\nEnter accounl nos,, names, and balances\n');
scanf ( 'olod yos %f', &1.n0, a1,acc-name, &a1.bal)
. scanf ( "%d %s %f', &a2.no, a2.acc_name, &a2,bal ) Figut€ 4. I StructurE elements in memory
scanf ("%d %s %fl, &a3.no, a3.acc_name, &a3.bal)
int no ;
float bal ;
slruct player
); {
struct account a[10i;
char name[2o] ;
int i, acc i
int age ;
float balance;
) pt = ( 'Nick Yates', 30 ) ;
As you can see the structure elements are still accessed using the
(b) The value ofone structure variable can be assigned to another
structure variable of lhe same type using the assignment
'.' opelator, and the array elements using thg usual subscript operator. It is not necessary to copy the struoture elements
notation
piece-meal. For example,
f Program 50 '/
I- 4oor I
8000
main0
{
struct
t
book "/ Figure 4.3
charname[2s]; CaD we trot pass the address ofa strucfure variable to a function?
char autDr[25] ; We carl. The following program demonstrates this.
inl callno j
Chapter 4: Pointers and Structures 197
196 Understanding Pointers In C
stuci a
f Program 51 -/ {
f Passing addrcss ofa structure vadable'/ siruct b
book
struct {
{ int i;
char namel2s]i ioal f;
charautho(2s]; char ch ;
intcallno ; ]x;
); struct c
t
mainO inl j;
( float g;
void display (strucl book
*
) charch;
struct book bl = { "Let us C", "YPK', 101 }; }y;
display (&b1 )i |z:
)
Suppose we make a call to a function as shorm bolou,:
void display strucl book 'b
( ) f b is a pointer to a structure '/
{ pdntf ( 1n%s\n%s\n%d", b->name, b->auhor, blcallno )
run ( &.y);
;
main0
(
-p
int i
struct a z;
clrsc( ) :
fun(&z,y):
pdntf ( 'h%d %t %c', z.x.i, z.x.t, z.x.ch ) ;
getch( ) ;
Figue 4.4
)
Let us understand this statement part by pad,
fun(sructc'p)
(
In the expression ( ( rtruct r * ) 0 ), 0 is being t)?€gasted into
int otfset ;
pointer to rtruct .. This explessiorl is pretending that there is a
structb*addEss;
vrriable of t)?e slruct r at address 0. The expression & ( ( ( struct
r t a * ) 0 ) -> y ) gives the addr€ss of sttuctur€ variable y. But this is
) ( & ( ( druct a' ) 0 )
ch c' -> y ) j)
otEst = ( ) & ( ( stuot
- (char') ( ( sfructa') 0 ); aot the base address ofthe shuoture c. Hence we haye typecasM it
addrcss = ( struct b ' X ( char' ) & ( p -> j ) - ohet ) ;
using struct c *. Using lhis address we can access the member J of
addr€ss -> i= 400 ; the slructule vadable y. Finally, aft€r taking the address of
address -> f = 3.i4 ; member j, we have t)?ecasted it using char * to make the
address "> ch r'd : subuaction po$sible. The statement to the dght of the '-' operator is
) straighdorward. On subtraotiotL we get the offset of member j of
structure variable y. Now using offset the base address is
In the above program shucturcs b and c having members i, f, ch calculated thrcugh the following statement.
and j, g, ch are nested within the stuctwe r with stnrcture
variables x and y of, stluotule b and c respe.tively. Next we have address = (struct b') (( char. )& (p -> j )- offset ) ;
called the fudctior fun( ) with the base address of drc stucture
variable y. Now &om fun( ), we wish to access the members of
200 Understanding Pointers In C
Chapter 4: Pointers and Structures 201
addafter ( p, 1, 99 )
lemp>link=r'
,}
dlsplay(p); )
printf ( '\nNo. of Elements in th€ Linksd List = y!d', ount (p));
f adds a new node at the beginning of the llnksd list '/
delets ( &p, 888 ) addalbeg ( sfuct node 'q, int num )
;
deletB ( &p, 'l ) i {
delete (&p, 10
slrucl node lemp ;
);
display(p)i I add new node '/
pdntf('\nNo. olelements in the linked llst= %d', count ( p) ); temp = malloc( sizeof ( structnode ) ) ;
l ) -
bmp dala num '
if ddds a node al'ttre snd ofe llnked lisl'1 temp>link='q
app€nd ( struct node
*q, lnt num 'q = temp ;
)
( )
*temp,
struct node 'r;
-q f adds a new node afrer the specilied number of nodes '/
temP =
" addafier ( slruct node 'q, inl loc, int num )
if (
-q
==
pg;-117',t*",st is empty, cleate first node'/ {
(, stuct node Iemp, 1 ;
{ retum c;
pdntf ( tl]herc are less than %d elements in list', loc ) ; )
relum ;
{ retum;
p ntf ( "%d ', q -> data ) ; )
q=q->tink;
I f deleles the intemediate nodes in the linked list./
) else
{
/'counts the numberot nodes prBsent in the linked list'/ old -> link = temp -> link ;
count ( strudt node 'q ) nee ( lemp ) j
{ Etum ;
intc = 0; )
)
/' traverEe the entirc linked list'/
)
while ( q != NULL f fave$e the linked list till the last node is reached '/
{ else
q=q->link; {
c++ ; old = temp ; f oH points to the prcvious node */
) temp =le" -' /'go b the next node */
) "n* '
206 Underslanding Pointers In C Chapter 4: Pointers and Structures 207
To begin with we have defined a structure for a node. It co ains a Then usitrg temp we have traversed tbrough the entire linked list
data palt and a link part. The vaiiable p has been declared as usitrg the stat€metrts:
poiflter to a node, We have used this pointer as pointer to lhe first
node in the linked list. No matter how many nodes get added to the while ( temp )
lini != NULL )
linked list, p wquld contiflue to pointer to the first node in the list temo = tsm, -> link j
When no node has been added to the list, p has been set to NULL
to indicate that the list is emptY. The position of the pointers before and after traversing the linked
list is shown in Figure 4.6
The append( ) function has to deal with two sihrations:
ll(-q == xU111
node being
added
Lastly p is made to point to this node, since the fiIst node has been
added to the list and p must always point to the frIst node. Note Figue 4.6
that *q is nothing but equal to P.
Each time through the loop the statement iemp = temp -> link
In the other case, when the linked list is trot ernpty, the condition makes temp point to the next node in the list. When temp reaches
the last node the condition temp -> link !: NULL would fail.
if (-q == xg11- Once outside the loop we allocate space for the rew node through
1
the statement
208 Understanding Pointers In C
the right hand side lelds 400. This address is now stored in temp.
r= malloc (sizeof{struct node )); As a result, temp starts poinling to the nod€ present at address
400. In effeot the statement has shifted t€mp so that it has started
..Onoe the spaoe has boen allocated for the new node its data part is pointing to the next node in the lisr.
stuffGd \rith num and the link part with NtlLL. Note that this node
is now going to be the last Node in the list. Let us now undeNtand th. addatbeg( ) functioD. Suppose there are
already 5 nodes in the list and we wish to add a new node at the
A11 that now remains to be done is connecting the previous last beginning of rhis existing linked list. This situation is show in
node with the new last node. The previous last node is being Figure 4.8.
pointed to by temp aod the new last node is being pointed to by r.
They are conn€cted through the statement
rE
temp "> link = r I
temp
Figure 4.8
Figure 4.7
For adding a new node at the beginning, frrstly space is allocated
Imtead of shov/ing the links to the next node I have shown the for this node and <lata is stored in it through the statement
addresses of the next Ilode in the link part of each node.
temp -> data = num
When we execute the statement
Now we need lo make ihe titrk pan of this node point lo the
temp = tgmp -> link existing first Itode. This has be€lt achieved through the statement
210 Understanding Pointers In C Chapter 4: Pointers and Strucnres 211
Lastly, this now node must be made the fiI5t node in Ore list. Thi$
If the node io be deleted is atr i ermediate node, then rhe posirion
has been attained tkough the stateme
ofvafious pointers atrd links before and after the deletion is shown
in Figue 4.9.
'q = temp ;
The filst statement mskes link part ofnode contaiuing 99 to point temp
to the node containing 4. The second staternent ensues that the J
lillk part ofnode containing 3 points to the node containing 99. On mt noa"
execution of the sccond statement the earlier link between 3 and 4
i _eJ_l _ _ -l+ geh deleted
After Deledon
is severed. So now 3 no longer points to 4, it points to 99.
The disptay( ) and count( ) functions are straiSht forward. I leave Figure 4.9
them for you to understand.
The rddafter( ) fihction pemits us to add a new node after a
'Ilat brings us to the last functio! in the prcgram i.e. dclete( ). Io specified number ofnode in the linked lisr.
this function through the while loop, we have traveNed thrcugh
the entirc linked list, checking at each node, whether it is the node To begin wirh, through a loop we skip the desircd number ofnodes
to be deleted. If so, we have checked if the rode being deleted is after which a new nod6 is to be added. Suppose we wish to add a
the first node in the linked list. Ifit is so,,we have simply shifted p new node containing data as 99 after the 3d node in the list. The
212 Understanding Pohtters In C Chapter 4: Pointers and Structures 2t3
position ofpointeis once the contol reaches outside the for loop is
shown in the Figure 4. I 0(a).
Fisue 4.10 Now that we have understood how a linked list can be maintained
how about ensuring that every element added to the linked list gets
A oommon and a wrcng implession that beginners carry is that a inserted at suoh a place that the liDked list is always maintained iD
linked list is used only for stodng integers. However, a linked list ascending order? Here it is...
can virtually be used for storing any similar data. For example,
there can exlst a linked list of floats, a linked list of names, or even f kogram 54'l
a linked list ofrecords, where each record contains name, age and f Program for adding and deleting nodes from an ascending order
salary of an employee. These linked lists are shown in the '/
linked list
follor/ing figure. #inclde 'alloc.h'
214 Understanding Pointerc In C Chapter 4: Pointers and Slructures 'rt<
f adds node b an ascending odei llnked lisi '/ f ha\€6e tle BnliIB linfed lM'/
add ( slruct node
*q, lnt num
) while ( q != NULL )
{ {
struct node 1, 'temP = 'q ; Ptinf('9{d',q}dab);
q=q>link;
r = malbc ( sizeol ( stl$t nodE ).) ; )
r -> dala = num ; )
234 Understanding Pointers In C
Chapter 4: Poinlers and Struch.res 23s
d_addabes (&p, 33 ) j
q=q">next;
d*addalb€g ( &p, 55 ) ;
f add a new node at he end '/
d_display(p); r= malloc ( sizeol( siructdnode ) ) ;
printf ( 'hNo, of elemenls in the DLL = %dvr,, d_ount ( p ) ) ; r)data=num;
r -> next = NLrLL ;
d_addafrer ( p, 1, 4000 ) ;
rlprev=q;
d_addafrer ( p, 2, 9000 )
q->next=ri
;
d-display(p); )
pdntf ( '\nNo. of Blements in the DLL = %d\n', d-count ( p
));
f adds a new node at the b€gining of the linked list'/
d-addatbeg ( stuct dnode
*s, int num
d_delete ( &p, 51 ) ; )
d_deleb (&p, 21 ) ; {
structdnode.q ;
d-disday (p );
f c.eate a new node '/
Chapter 5: Pointers and Data Structures .28t
280
add &first 1 )
havo several data struohues share the salle spaqe, without paying add &flsl 2
partioular attention to their relative size at aay time. add &lirst 3
add &first 4
The seoond advantage of litrked lists is that they provide flexibility add &lirst, 5
in allowing the items to be rearanged efficiently. This flexibility is add &frst 6 )
gained at the expense of quiok access to aay aIbitary item in the add &first 7 )
list.
clIsc( ) ;
Irr this chaptq we would write pro$ams to perfom more pdnil('Firstlinked list :' ) ;
complicated operations on the linked list, We would also find out display(frst);
ho\l. linked lists catr be used to matltain polynomials and pdnf ('hNo. ofelements in Linked List: %d' , count (first ))j
manipulate them. Let us begin with merging of two linked lists.
add &s€cond, 8 ) ;
add &second, I )
Merging of Linked Lists add &se{ond, 3 )
;
;
add &sec.nd,4 ) i
Suppose wo havc two linked lists pointed to by two independent add &second, 5 ) ;
pointas and we wish to merge the two lists into a third list While add &second, 6 ) ;
iarrying out this merging we wish to cnpure that those elements add &second, 7 )
which ire common to both the lists occur only once ir the third
;
list, The plogram !o achieve this is given below. It is assum€d that pdntf ( h\nsecond linked list : " ) ;
within a list all element! ale unique. display ( s8cond ) ;
printf ('\nNo. of elements in Linked List: %d" , count ( second
)) i
f Pmgram 60 '/
f PIogEm to merg8 h o llnked llsb, Estlicting lhe common denents b merge (liM, second, &thid ) ;
occur only onc€ '/
#lnclude 'alloc,h' prinf('V nThe concatenated list i " ) ;
display ( lhird ) ;
slruct node pdntf ("hNo. of elements in Linked List: %d', count (third ) ) j
( )
int data ;
suuct node 'link ; f adds node to an ascending oder linked list'/
); add ( struct node "q, int num )
{
main( ) stlct *q
node 'r, lemp = ;
{
struct node'llEl 'second, 'tlid ;
irst = second : thitd = NULL ; f empty linked lisb'/
282 Understanding Pointers In C
z=z->link;
's = malloc ( sizeof ( struct node ) ) ; z>data=p)data;
z='sj P=Pllink;
) )
else
{ f end ot second list has been reached '/
z -> link = malloc (sizeof (struct node )); while (q != NULL )
z: z->.link; (
) z-> link = malloc (sizeof(struct node )) ;
z=z)link;
if(p->data<qldata) . -1 6316 = q -> dala ;
( q=q->link; .'
z>data=pldatai )
p= p.> llnk i z-> link = NULL;
) )
else
( In this program, as usual, we begin by building a structure to
if(q->data<p">data) accommodate the data and link, whioh togeth€! represent a node.
{ We have us€d pointers lirst, Becotrd and thlrd to point to the three
a.16216 = q -> data i linked lists. Since to begin rvith all the three linked lists are empty,
q=q_>link; these pointe$ contain NULL. Next, by calling the function rdd( )
) rcpeatedly two linked lists are built, one being pointed to by lirst
else and other by the pointer secotrd. Finally, the merge( ) function is
( called to merg6 the two lists into one. This m€rged list is pointed
if (p -> data == q -> data ) to by tlre poider third. While merging the two lists it is assumed
( that the li$ts themselves are in ascending order. While building the
z -> data = q -> data; two lists the add( ) function makes sure that when a node is added
p=p->link; the elements in tlle lists are maintained in ascending order, While
q=q->tink; merging the two lists the merge( ) firnctions accounts for the
) possibility of any ofthe two lists being empty,
)
) Linked Lists and Polynomials
)
Pollaomials like 5x4+2xl+7x2+10x-8 can be maitrtained using a
f if end of first list has not been rcached '/ linked list. To achieve this each node should consists of three
while (p l= NULL )
( elements, nahely coefficient, exponent and a link to the next term.
z -> link = malloc ( sizeof ( struct node ) )
While oaiotaining the polyromial it is assumed that the exponent
;
286 Understand.ing Pointers In C Chapter 5: Pointers and Data Structures 287
ofeach successive telm is less than thal of the previous t€mr. Once display_poly(frst);
we build a linked list to rcFesent a pol)aomial we can use such
poly_append ( &second, .5, 6
lists to perfom common polynomial operations like aildition and 1
/' structure represenling a node of a linked list, The node can sbe tem ot a
polynomial 'i f dEns a dash€d honzontal line '/
pdntl( 1,l');
struct polynode
uiile ( i++ < 79 )
{ printf('-')'
lloal coeff i
Binary Trees
FigurE 5.14 illustates $omc stuctures that are not binary tees.
Be
Let us beEin our study of binary trees by discussiag some basic suf,e flrat you urderstad why each of theur is not a binary tee as
just defued.
corcepts and terminology. A simple birtary tiee is shoBn in Figure
5.13.
(a) (b)
Figue 5.14
Figure 5.13 Let us ron, get itscd to some more t€rmitrolory us€d itr association
with binary tr€€s. IfA is 6re rcot of a binary;€e ana S is til;;i
-be
A binary tee is a finite set of elcmelts that is either empty or is of ils leff or right subtreg 0ren A is said to the fether of B anrt
pa(itiorcd into three disjoint subsets. The first subset cootains a B is said to be the left or rlght solt ofA. A nodc that has no sons
single elsrnent called the root of the hee. The other two subsets (such as-D, c, E, or I of Figure 5,13) is called a le!f.
In geneml
are themselves binary tEes, called the left and right subtrees of
1ny mde say ll], is ar atrcestor of node n2 laudni ie a
the original tree. A lefl or ight subtlee oan be empty. Eaoh descendant of nt) if nl is either the fatber of rl2 oi the frther
element of a binary tree is called a node of tte tlee atrd lhe tree
oi
some ancestor ofD2. For exatrple, in the tree of Figue 5.13,
consists ofnine aodes with A as its root. Its left subtree is rooted at
A is
an anoestor ofc. A node tr2 is a left dercctrdrnt ofaode nl ifn2
B and its right subhee is moted at C. This is indicated by the two is either the left sotr of trI or a descendaot of the left son
of nI. A
branches emanating ftom A !o B on the left and to C on the right. rlght dercetrdatrt may bc similarly defined. Two nodes are
I'he absenoe ofa bmnch indicates an empty $ubtree. For example, brothers iftbey are left and right sons oftbe same fathsr.
the leff subtree of the binary tree rooted at C and the dght subtree
of tlle binary tree rooted at E are both empqr. The binary tre€s Although @tural trees grow with their roots in the grouod and
rooted at D, G,E atrdI have empty ght and left subtees. their leaves the ai!, compute! scientists almost -universally
-in
portray tr€e d4ta structues with the root at the top aad
the leaves a:t
Yaileu+A K/",ellr/",
ForJ ('proiriU tn(r lit'r rrrlhour n,,inr,:rs i\ rt'c $itl,out t(,od
He nrc.l. rnorc rhan iu.r - norlJrng.r.qurinrrnre rrlth
lotnter.
tl Ite dcsrre. ro c\flol lh<ir rrnrnen-rc f,.renrtal p,,illef,lrercni
Pos(r arld l,rnch arrd rhis hook corcr.. rrenrhrng rllar ha-
:rn)lhIg ru LI' srrh lo'nrrrs in r .irrrplr. ..,.i-ro rilr,ler.run,l
l{.1}. I hLi t'rplcs (r,\!'rcd Jre:
$€bsite : $arn:bpbonlitre.com