You are on page 1of 255

i

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

3. Pointers and Stiitrgs ,.....................133 6. PointersMisceIlrtry..,,,.....................................................391


Wat are Slrings, 1j3 File Poi rets, 391
Stqhdard Library String Funcrions, I38 Pointers to Functions, 394

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

f f Tbich featue of C do beginners find most difficulr to


VV understand? The answer is easy: pointers. Other
v V languages have pointeE but few use tbem so freely, with
such abandon, as C does. Aod why rct? Ir is C,s clever use of
pointeN that mak€s it the excellent language it is.

The difficulty begiDners have with pointers has much to do with


C's pointe, terminology than lhe actual concept. For instance.
when a C progmmmer says that a cedain variable is a . pointer..,
what does that mean? It is hard to s€€ how a variable can poinr to
something, or in a certain direction.
2 Understanding Pointers In C Chapter 1: An Introduction to Pointers 3

It is difficult to get a grip on poioters just by listening to 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, )

inti=3; l'he output ofthe above program would be:


This declaration tells the C oompiler to: Addrcss ot i= 6485
Value of i= 3
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location. l,ook at the fi$t printf( ) statement carefully. The .&, opeBtor
(c) Srore the value I ar this location. [sod in this statement is C's 'address of operator. The expression
&i retums the address ofthe vagi4llglwhich in this case happens
We may rcpresent i's looation irl the memory by the following lo be 6485
memory map:
other pointer operator avaikble in C is '*'. called 'value at
ult ess o erator. It retums the vaiiE stored at a particdlalEddfess.
r\, e'value at address' operator is also called an 'indirection'
i-__} Location Dnme

El--*
6485+ I-ocation no. (Ad&ess)
orator.

l,hlene carefully the output olthe following programj


/' Program 2 '/
nrain0
Figure l.l I
inti=3;
We see that the computer has selected memory Iocation 6485 as printf ( "\nAddress of i = %u', &i) ;
the place to store the value 3. This location number 6485 is not a printf ( \nvalue ofr = %d-, i) ;
number to be relied upon, because some other time drc computer printi ("\nvalue of i= %d",.(&i));
may ohoose a different location for storing th€ value 3. Ttre )
impofiant point is, l's address in memory is a number.
IJnderstanding Poinlers In C Chapter I : An Introduction to pointers
4 5

As you can see, i,s value is 3 andj,s


The output ofthe above prog€m would be: value is i,s address.

use j jn a program wilhout dectaring


Addressoli=6485 ". :an'r
j rs a \arjable. which conlains lhe
"l:1^1"]!
8rn.e it. And
Valueofi=3 addre., of i, it is-aeilurea-
0r.
Value oli = 3
lnl 'j
Note that pdnting the value of *( &i ) is same as printing the value
;

ofi. 'lltis declaralion


tells the compiler that I will be used
rddress ofan integer value _ in lo store the
o*re. *Jro.; poino ,o _ iri"g;;
Pointer Expressions Ilow do wejustify tlie usage of * in
the declaiation,

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...

Value ofj= 6485


Valueofk=3276 The Jargon of Pointers
Valueoli=3 Consider the following program segment:
Valueofi=3
Value of i= 3 inta=35;
Valu6ofi=3 inl 'b :
b=&a;
The following memory tDop would help you ir tmcing out how the
Now can you guess which ofthe follo.\f,ing statemenis are coneotl
prcgram prints dle above outpul.
(a) b contains address ofan ht.
(b) Value at address contained in b is an lnt.
(c) b is an ltrl pointer.
I J
k (d) b points to an t!t.
3 6485 3216 (e) b ig a pointer which points in the dileotion ofan lnt,
6485 3276 1234
well, all these starements arc corect. That,s poinrgr jargon for
you. All the statemenls are fying to establish t:he srfle fact: tlBl
since b oontains address ofanint-it's an int Dointer, ,ikewise, hao
Figurc 1.3 b contained an address of a flort it would have beoome a flolr
pointer. with the same argument if we have three Doiflter variableg
Obs€rvc how the variables l, J and k have been declarcd, first containing addrcss oian array, second contai;ing ad&ess ol,a
structure and third containing address of a fuflction then It woulo
inti; be appropliate to call these ai an array pointer, a structure poinler
-l
lnl i
and a fiinction pointe! respectively.
int -k i

is a pointer to ar lnt, whsreas k is a


char, int zad.Jlod, Pointers
H€re, I is an ordinary ldt, I
poiflrer to a pointer. ln pdnciple, there could bG a pointer to a Considei the followiog program:
;ointer to a pointer, or a pointer to a pointer to a pointer to a f
pointer. There is no limit on how far can we go on extending this
P@gran 5'/
main( )
a€finition. Possibly, titl the point we can csrFehetrd it' And that
{
point of oomprehensiotr is usually a pointe, to a pointer. Beyotd charc,'cc;
int i, 'ii;
Chapter 1: An Introductia to Pointers t1

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
, ,

Address conhined in cc = 1004


*ll and *aa allow access !o all the bytes occupied by the intcger I
Addr€ss contain€d ln il = 2008 and a rcspectively. This is because il and a& haye been dcclarcd as
Address c.ntalned in aa = 7006 itrt and llort pointers respectively. Since il is an itrt pointer, *ll
Vslue ofc = A must fetch ar lrt. Similally, since aa is a flort pointer *ar must
Valui of i: 54 fetch a lloat.
Valueofa=3.140000
Do you &ink the following program would work? And if it does
Note that in the prltrtf( )s the addresses of chrr, lnt ard lhe no't what would be its puttr ui?
all have been prioted using the fomat specifier 7ou, Sometimes
the address miy tum out to be a number smaller than 32767. ln f ftogram 6'/
such a case we may use the fomat specifier 7"d to pritrt the main( )
address. Also observe that though the integer va able i occupies {
two brtes in mernory the stalement ii = &l stores only the addEss inli=54;
ofthe first blte, 2008 itr il (refer Figurc 1.4). Similarly, = &a float a = 3.,l4;
stores only the address of the flrst byte (7006) out'of "
forE bytes char'ii, 'aa ;

occupied by the float variable a.


ii= ( char . )&i; ,13
aa=(char.)Aa;
pdntf ( lnAddress conhined in ij = %u', ii ) i
prinf ( lnAddrcss onhined in aa = %u', aa ) ;
pdntf ( lnvalue at fre address conhined in ii o/od', ) :
12 Understanding Pointers In C Chapter l: An Introduction to Pointers 13

p ntf ( "hvalue at lhe addrcss contained in aa = %d', 'aa ) ; (


) inta=10i
irt b= 20;
Note that here and aa have been declared as chsr poioters. Still
ll
rhe statemenrs ll = &i and ra = &a worElqnce again tbe ad&esses swapv(a,b);
2008 and 700d (refer Figure 1.4) get stored in ll and m which are pdntf(tla=%d",a);
printed through the first two prtntf( )'s. However, the prcgram printf('bb=%d',b);
falte$ at the next two prttrtf( )'s. This is so since ll is a character )
pointsr *ll gives value at .d&ess 2008 ard not lhe one presetrt at
2008 ad 2009. Similarly, *ra gives the value at 7006 and not the
swapv ( int x, inl y )

one contained in 7006, 7007, 7008 and 7009. {


inlt;
Moral is, ifyou vdsh to acoess an integer value stored in a variable
t=x;
x=y;
using its addr€6s, it's rccessary that the ad&€ss be stoEd in an y=t;
integer poiater. Likewise, ifyou wish io acoess a float value stored
in a variable using its addrcss, it's necassary to storc the address in pdntf(\u=%d",x)i
a float pointer.
Printf (\y = %d", y )'
)
Passing .dddresses to Functions
The output ofthe above program will be:
Aryu.ments arc generally passcd to fulctions in one of the two
waysr x=20
v= 10
G) Bending the values of the arguments a=10
(b) sending the addresses ofthe arguments b=20

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

/* Program 10-t Solved Problems


main0
{ lAl What will be the output oflhc following programs:
int'p;
-fun0
int ; /" prototype declaration */ (1) main0
P=fun0; t
printf ( '\n% u",p); int i= -5, j= -2;
printf ( "\n%d",-p); junk (i, &j);
printf ( '\ni = %d j= %d", i,l );

int *iun( ) /- function defnilion */


t junk ( int i, int tj
)
inti=20; (
relurn(&i);
) l- I li
)
This progmm shows how a pointer can be rctumed from a
funotion. Note that the prototlpe declaration tetls the compiler that Output
fun( ) is a function which receives nothing but returns an integer
pointer. The first prlntf( ) would output the address contained in p -5j
(address of l). Can you guess what the second prlntf( ) would
output? No, it won't p nt 20. This is because, when the control Explanation
comes back from fun( ), I dies. So sven if we have its ad&ess in p
we can't access I since it is aheady dead. If you want I to survive
and *p to give 20 then make sure that you deolare i as stafic as One doubt immediately oom€q to the mind----can we use same
shown below: variable names in differcnt functions? Yes, by all means,
without absolutely any conflict. Thus, the two sets of i and J
static int i = 20 ;
are two totally different sets of variables. While calling the
function junk( ) the value ofl and the address ofj are passed
to it. Natumlly, in ju*(
) i is declared as an ordinary int,
whereas. j is declared as a pointer to an int.

Even though the value of i is changed to 25 in junk( ), this


ohange will not be refl€cted back in main( ). As against this,
since j's address is being passed to junk( ), any change in
Jutrk( ) gets reflected back in maitr( ). Hence -J- *j, which
evaluates to 4 is reflected back in main( ).
18 Understanding Pointers In C
Chapler 1: An Introiluction to Pahtters 19
(2) #include "stdio.h'
main( )
While fiading out size of NULL, we are truly sDeakine
findiog out size of 0. This is an htieger, hence- its'size ii
{
rcported as 2 bytes.
int a, b =5;
a=b+NULL;
printf('%d',a); Even though the string -' is empty it
still contains the
) character, '\0'. Hence its size arrrrs out to be I bvte,

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
(

-) printf ( '%d %d', sizeof ( NULI-


), !*zeof(.. ) ) ;
b oontains the addrcss ofvariable r. Since a is a floaq b must
be a lloat pointer. The same address is then assigtred to c.
Therefore c has also been declared as a f,oat pointe.. The fiIst
Output
prtntf( ) prirfs the address of a in three differcnt ways. No
problem therc. What is supdsing is the output of the second
21
printf( ). Through this pritrtf( ) we are attempting to print
7.999999 by. applying pohler operalors on a, b and c. a,
Explanotiot *(&a), *b, *c all yield 7-999999 but when'they are prinred
using yod, printf( ) blows it up as the ouq,ut above would
justiry.
20 Understanding Pointers In C
Chapter l: An Introduction to pointers 2l
So always remember to use 9/"f to print floating point values.
are assigred to p aDd q. The[ in the next
Don't rely on printf( ) to truncate a float value to an integer statement the
conditional operato$ test the value of i against
du ng pinting by using a yod. Vice versa also it is t[ue. The either the adtlress stored in p or the adjress
4j, anJ ;;tu;
following statements wouid not print 7.000000. Don't be appeaE that this address would be collected
,t""J f"tiil.
suryrised ifyou get some odd value. In that sense y"d and ohf in c in maijt t
are a Iittle unreliable.
and then would be printed out. Ard tb"* li". ;";;;;. A';
)
lirnction check( is not capable of retumins
an inteser
pololer. All that it ca! reEm is an ordinary
inti=7; intefer. Thus j"ust
declaring c as an iDteger pointer is qot sufficient.
printf("%f',i): We must
make the following modificaaioru in the progmm
to make it
work properly.
(s) mainO
(
, int.c; main0
(
c=check(10,20);
int 'c j
printf("hc=%u',c);
inl 'check ( in! int ) ;
)
c = check (10, m );
pdntf(tuc=%u.,c);
check ( int i, intj)
( )
int 'che6k ( int i, int j
int.p, rq ; )
p=&i;
q=&j;
if(i>=45)
retum (p )
);
else
(6) main( )
retum (q ) ;

)
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 )++

OutPut (2) !r th€ followinS gogrm add a stat€.ri€ot in the fi[roiion


q bebtB call = silg8
fu( ) such tllat ad&ess oft gels stored h l.
q aier call = 5502 L

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

At lot ofplaoes, some ofwhich are: Eiplanation

- Accesshg array or s&ing elements


No. An efior would be .eported i[ the statement k+ slnce
- Dynamic memorY allocation
arithmetic on void pointeE is Dot permitted unless the void
- Call by refereace
pointer is appropdately typ€casted.
- Implemeding lioked lists, tre€s, $aPhs and many other
data structures (7) Would the following prograrn give any wamiug on
grYe a comPilatioo enor or compilatioo?
(5) Would the following Eogram
waming? <Yes/No> #include 'stdio-h'
main0
main0 (
( int'p1, i= 25;
ioat i = 10,1; void .p2 ;
bid'k; p1 =&;
k=&i; p2=&i;
j= k; p1 = p2:
pdntl(ln%f,l); p2=p1;
) )

Erylaaation Expla ariqn

No. Here no tipecastirg is required while assiguing thc value


-*Jto. No
t I L""ugrao*lsioq" ,"t" uopl&d-gU@or'"ntlv
*teo ooo po-i"tertypes are assigned to atrd fiom vold '' (8) Would the following program give atry waming on
compilatioa?
(6) Would thc followiag Pmgr& contpile? .

#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

(12)Is the NULL poirti:r same as an uoitritialised pointer?


<Ye$No>
Yes. The wamfug wonld be "Suspicious pointer conversion itr
firnction maitr( )".
Explakation
( 9) What is a oull point€d
No
Explanation
(l3)What does the error ..I{ull pointer Assignment,
mean and
what causes this e.rofl
For each pointer typ€ 0ike say a char pointer) C defines a
speoial pointer value that is guara eed trot to point to any Explanation
object oi fiuctiotr of that type. Usually, the null pointer
consta used for rcprcse itrg a dull pointer is the integer 0.
The Null pointer Assignment eEor is generated
only ia small
-Ud WUf" fi" Aff"r.o"" between a null pointer. a NULL macro. ard medium memory models. This error occurs programs,
in
the ASCII NUL character and trullstring? which attempt to cbange the bottom ofthe data ,"gJ;t..-----'

Explanatiot In Borland,s C oi C+ compilers, Borland places four zero


bltes at the bottom of the data segmetrt, followed
bv the
Borland copyright ootice ..Borlaod C++ - C"pv"gf,ii;i
A null pointer is a pointer, which doesd't point a[ywherc' Bodand Intl.". In the small and medium
-".ot;;"i;;;
null pohter points to DS:0000. Thus assignhg u ;ulu;
A NULL nla ro is us€d to represeot the trull pointet in source memory refer_enced by this pofuter wilt ov;rwri-t" tte
;;;
code. It has . value 0 associat€d wilh it. l D,,le In fie data segnent. At progmtD terEination,
nrsi ."io
the four
zercs and rhe copydght bamer arE ch€cked. Ifeithei
The ASCtr NUL character has all its bits as 0 but doesn't has been
mo.difie4 then rhe Null poiDter Assigftretrt error is generated.
have any relationship with lhe null pofuter.
Note that the oointer may not truly be Du[, bur
maibe a wild
polnter that rcferences these key arcas in the data
The trull string isjusr atrolher oame for aD empty string "". sigrnent.
( I4 ) How do we d€bug a Null poifter Assignment
(l l) In which header file is the NULL rnacro defined. erlor?

Explanation
Explanotioa

, In files "stdio.h" and "stddef.h".


In the lrtegrated Development Ellvironltre set two
watohes- -olre pohting to the bottoE of,tlE data
segnent and
another pointing to the banne. (refer (13) above
for details).
1e Undennnding Pointen In C Chapter l: An Introduction to pointers 29
These wat hes, ed what they should display in the watch the key values at the base of tbe data segment. Modifuing
window, are: the
base ol systern memory usually causes a system crash,
however. Allhough it would be possible that a vrild pointer
'(char J4,42MS 'Borland C+r - Copydght 19gl Bodand lntl.,
would overwrite the key values, it would Dot indicale
(ch ')0 NU|I pojnter. It the tiny memory model, DS = CS SS.
a null
= fterefore,
using a null pohter will overwrite tb€ beginning of the
Of course, the copyright bamer shown above will vary code
segment.
depending otr your ve$iotr ofthe Borland CyC+ compiler.

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);

rhi' ICI What do the following declarations stand for?


sfEpy ( pt, );
s[cpy ( banner, 'hello') ; int
*i ;
pdttf ( lncood iloming' ) ; ,loat -i ;
) char*k;
Nole that a Null poiDter Assigtrmetrt ermr is trot generaled in voidf(int',chart);
all models. Il the compact, hrge atrd huge memory models, floattg(floatt,ioal-);
frr pointgrs are us€d for data (Refq C-nupte" O fo, -o." int*h(foat',char-);
mfonytion about m€mory models and far pointers).
Therefore, a null poiater will reference 0000:0000, oi tle tase b.plahatiot
ofsystem memory, atrd using it will trot cause a comrption of
30 Understanding Poinars In C Chapter I: An I trod ction to Pointers 31

I is a pointer to a pointer to a pointer to an itrt.


(2) mdno
j is a pointer to a pointer to a lloat. {
shar c, 'cc ;'
k is a pointer to a pointer to a pointer to a pohter to a char. inti;
long I ;
f is a function which receives an itrt pointer alld a char ioal t;
pointer and rctuIus trothing.

g is a function whicb receives a float pointer and a poinler to i='15;


a float pointer and in fum rehrms a float pointer. I = 77'177 i
f= 3.14 ;
h is a function which receives a flort pointer and a pointer to cc = &c;
a char pointer and in tum rcfums a pointer to an itrt pointer. trc = %c cc = %u', 'cc, cc ) ;
pdntf (
cc=&;
pdntl('bi= gtd cc = %d, *cc, cc ) ;
&l;
cc =
(1nl= %ld cc = %u', 'cc, cc ) ;
printf
cc=&l;
pdntf ( 1nt = %f cc = %u', 'cc, cc ) ;
)
(3) maino
Exercise
{
intcr10,d=m;
IA I Wtat $r'il1 be lhe output ofthe following programs:
pdntf \We ale in main( )....') ;
(1) maino pdntf lnAddtess orc= %u Address ofd = %u", &c, 8d ) ;

pdntf lnBebre srflBp( ). c=Yod d=%d',c,d);


{
int a, 'b,
*c, *d, *e ; swap c,d);
printf \!Bek b main0....'):
a=10; pdntf \Afldr swaD( ), c=%d d=Yod',c,d);
b=&a;
)
c=&b;
d=&c; swap (intc, inld )
e=&d;
{
pnntf ( 1na = %d b = %u c = %u d = %u e = you', a, b, c, d, e ) ; pdntf ( lnwe ale in ${ad )....' ) ;
pintf ( 1n%d 96d i{d', a, a + rb, *c + Ed + );
tre
printl ( lnAddless ofc = %u Adrcss old = %u', &c,8d )j
) pdntl (1nBetore chang€{ ), c = 96d d=yod',c,d);
Chapter 1: An Introduction to Pointers 33
32 (lnderstan"ding Pointers In C

'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,

,_cc .dd &product) ;


= ;
Chapt* l: An Introduction to Pointers 35

rctum (&product); &i= 7200 ;


) printf ( lnneu ydue ofi = 96d neflddless of i= %u", i, &i):
)
4) main( )
{ (11) floata = 3.14;
char'c = 4000 ; float
*z
;
inl 'i = 4000 : foal *y j
long
.l
= 4000 ; float
*x;
float 'f =,1000 ; foal *v:
double 'd = 4000 ; float
*u, ;

printf ( \E=%u, c+ 1 = %u', c,c +'l ) float


* tun1 ( ioat ') ;
pnntf ( 1ni = %u, i + 1 =%u', i i+'l ) ; tloat* tun2 (float-);
pnntf ( trl= %u, l+ 1 = 9tu', l, l+ 1 );
printf ( \f
= %u, q-+'l =%u', t f + I ) : main( )
printf ( \d
= %u, d + 1 = %u', d, d + 1 ) (
) clrsc( );
z=tun1(&a)l
maino pnnfr ('VNiA? ,a*zl i
{ )
int i= 10, j = 20, difl;
;oat*fun1(foatt)
. diff= &j- Ai: (
pdntf("haddEssofi=%u atffIess oli = %rf, &i, Ej); Y=82;
pdntf ( 'hdtfeGnce ol addrEsses of i and j is %d'r'diff )i v=fun2(&y);
) retum (*Y ) ;
)
main0
{ float
-* tun2 ( float "x )
int'i,'jj {
j=i'2; w=&x;
Pdntf(1nj=o/6u',i) ' retum (w);
) )
(10) main0
( lDl Strte True or False:
int i= 10:
pdnf (1llvalueoli=%d add€ss ofi = %u', i, &i) ;
(l) Multiplication of a pointer and an uDsigred integer is
allowed-
No matter how much time
{2 ) Address of a float cao be assigned to a chlr poiioter. rox hove q)ent with pointers you y,/auld
(3) A float pointer alwa]rs cotrtaitrs a whole rumber. always l d so,rre application oft that woutd leave yoi guessing.
(4) A pointer p contaitrs addre$s ofa pointer to a'pointer to an
iirteger pohte.. To reach the integer value we should use

Sointm antflrays

f he C language providas a capability callecl array that enables


the user to design a s€t of similar data types. Array is a very
I
^
lhe
popular data type with C progrmrnoers. Tbis is because of
convmience with which arrays IeDd thernsolves to
programming. Pointers and arrys are so closbly related rhat
discussing arra)r$ without discussitrg poitrtels or vice versa would
make the discussion incomplete and wauting. In fact all armys
make use ofpointeE intemally. HeDce it 6 a[ too rclevant to study
lhcm togelher rather thaD as isotaled topics.
38 Understanding Pointers In C

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.

Passing Array Elements to a tr'unetion


same place Army elements can be passed to
1e) If we so itesiro an aiTay catr be itritialised at lhe a furctiotr by callitrg the furction:
where it is declared. For exarple,
(a) by value, i.e. by passitrg values of array elements to the
int num[6] = { 2, 4, '12, 5, 45, 5 } i function
int n = ( 2, 4, 12, 5, 45, 5 ) i (b) by refercnc€, i.e_ by passiag addre*ses ofaray elements to the
ioat pressl] = { 12.3,342, -8.4, -11.3 }:
function.
(fl Ifthe anay is itritialis€dwherc it is defind mentioning the Programs showing how these calls atE made are given below.
dimension of array is optiooal as in second oraqle above'
l' Pto$am 12'l
f ./
(g) If the army elemetrts a€ not givetr atry specific valucs, they Demonstralion ol call by value
main0
are supposed to cotrtaitr ga6age values
(
(h) intii
In C therc is tro check to s€e ifthe subscript used for an array
int ma s[] 6t
exceeds the size of the dray. Dat e'ntered with a Eubscript = ( 55, 75, 56, 7S, 78, 90 ];
exceeding the array size will simply be plaoed in memory for(i=0;i<=6;{+})
ousiite tie anaft probably oa top of orher data dl ofl the display(mdksll);
program itsetf. 'ifris witt load to uprcdiotable results, to 6ay
iheicast, anrt there will be no error messag€ to wam you that
l/
vou are goilg beyond thc array size"In some cases the dlsplay ( int m)
iomputer rnay just harg. Thus, th€ following progam may (
tum oul to b€ suicidal: printf ('h%d', m);
l
f ProgEm '11
'/
main( )
And here's tbe output...
{ 66
int num[40], i; 06
for(i=0:i<=100;i+|) 76
42 Understatding Pointers In C Chapter 2: Pointen and Arays 43

56 Here, we are passitrg addrcsses of individual array elements to the


78
functioo displsy( ). Herce, the variable in rphioi this addrcss is
78
collected (n) must be a pohter variable. And sitrce n contains the
90
address of array elemetrt, to pdtrt out the arrly element we must
use the 'value at address' operator (*).
Here, w€ arB passing ao individual aray el€inent at a time to the
tunctiotr dtsplay( ) aod getting it pdnted in the tunctior dtiplay( ). Read the following p.ogram carefrlly. The pu4rose of the firnction
Note that since at a time ody otre elemeot is being passed, in the
is to just display the arlay elernents on ihe icreea. The program is
functiotr it is collected in a
odirary integer variable m.
only patly complete- you are required to *dte thi iraction
show( ) on yow olvtr. Try your hand at it.
And mw the call by referenc.e.

/. 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

Original value in x = 1002


=i-5;
k=j-6;
Original value in y = 2004
Original value in z = 5006 word of caution! Do not atterEpt Ore fullorrilg operations
lnicrs,.. 0ley would nev€r wort out
New value in x = 1004
New value in y = 2008 Addition of two 1,oioters
New valu8 in z = 5007 Multiplying a pointer with a numb€r
Dividing a pofurter with a atutrbcr
Chapter 2: Pointers and Anayq 4Z

pintf ('addrcss= %u', &numll) ;


Now we will try to corelate the following two facts. which we i*j
have already leamt: )
]
(a) Array elements arc always stor€d itr contiguous memory
locations. The output ofthis program would be:

(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.

Figure 2.1 f Pto$anj7 'l


main0
Herc is a program that prints out the memory locations in which (
the elemenls ofthis aray arc stored. inl numl] = { 24, 3d, 12,44,56, 17 };
inti=0i
f Program 16'/
main( ) (i
while <= 5)
t (
int nunll = 124,U, 12, 44,56, 17 |i printf ( '\naddrcss = %u ', &numfl
) ;
inti=0; prjntf ( tlement %d', numlil
= );
l++ ;
while (i<= 5)
)
{
printf ( \elementno. 96d ., i ;
)
48 Understanding Point*s In C Chapter 2: Pointers and Atays 49

The output ofthis prcgram wottld be: In this piogram, to begin with we have colleoted the base address

address 4001 element = 24


of the array (address of 0s element) in the va.iable using thej
= statement,
address = 4003 element = 34
= 4005 element =
'12
address
address = 4007 element = 44
j= &numlol; f assigns addr€ss,Oo1 b j'l
address = 4009 demem = 56
address = 4011 elemenl =
'17
When we arc inside the loop for the first time contains thej
address 4001, and the value at tlds addrcss is 24. These are printed
using the statements,
The next method accesses the array elemeDts using poioten

/'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

Note that $e addrcss of the zercth element (often klown as the


Passing an Entire Array to a F unction base addrcss) can also be passed by just passing the name of the
anay. Thus, the following two function calls are same:
Earlier we saw two programs one m which we passed individual
elemeds of an array to a firnctio4 and another io which we passed
0qisplay(8num[0],6];
addresses ofindividual €lernents to a funotion. Let us now see how
\/isplay(num,6);
to pass the entile aray to the function rather tha[ individual
element.s. Consider the following exarple:
The Real Thing
f Program 19'/
main0 If you have g$pg{ the concept of storage of aray elements in
memory alrd the arit metic ofpointeG, here is some rcal food for
t
int num[] = {24,3'1, 12,,14,56,17}; thought. Once again coNider the followi[g aray.
display(&numlol,6);

display ( int'j, int n )


{ 4001 4003 ,1005 AOM 4009 4011
inti=1;
while(i<=n)
(
Figre 2.2
Pdntf ('VElemenl = 9dd', l );
i++; This is how we would declarE the above atray in C,
j++ ; f increment poinbr b pointb next localion ?
) inl numll={23,34, 12,44,56, ,t7};
)
We alread_y, know tbat oa meotionilg the name of the array we get
Here, the dlsphy( frmctioa is us€.d to print out the array
) its base address. Thus5 by sayhg raum we would be able to r*er
elemeffs. Note that addre$s of the zcmth elsn€ is bciag passed
to the zercth clement of the arfif,-ilralTfZf GeraD-Easi[sEe
to the dlsplry( ) fitnction. The while loop is same as th€ oDe uled
that *truE a+L1fl![.+ql!q!Lr€Gr
in the eadier prograri to access lhe array elernents using pointers. !o Z:. SimiUay, Uy saying
'( Ium + I ) we cat! rrf€t to firstat,ndDt of t[e array, that is, 34.
In facl tlis is what &e C comller iniemally does. Wieo we-say,
Thus, just passing.lhe address ofthe zeroth elemeDt ofthe array to
num[il, the C compiler iatcrDally cotrv€{ts it to *( num + I ). This
a furction is as good as passiry tbe entire aray to lhe firnctionr It
mealts th.t all the followin€ ootatiotrs at€ !ame:
is also necessary to pass the total number ofelements io the array,
otherwise lhe dtuphy( ) fi.mctioo would not know when to
numliJ
termjrEt€ tte vhlle loop.
'( num + i)
52 (lndersnnding Pointers In C Chapter 2: pointers and Arrays 53

-ii+num) diftensional array is also called a mafix.


Here is a samnle
ilnuml
progam rhal initialises a 2-D array and print,
orai;.1".;"; ""''
And here is a prcgram to prove my poht. f Prcgrcm21|'t
maino
f Pmoram 20 '/ ti
{
int stud[s][2] =
f Acc-essing anay elements in difierent ways {
l1 main( ) 11234,561,
{ 1t212,331,
'17
int numll = { 24, 34. 12,44,56, } : { 1431, 80 },
inti=0; 11312,78),
11203,751
while (i<= 5) );
{
int i, i;
pdntl ( \address = %u ' , &numll) i

printf ( 'element = %d '. num0 ) ; for(i=0;i<=4:i++l


pdntf ( '%d ', '( num + i) ) ; {
pnntf ( 'Yod ', '( i + num ) ) ; prjntf(h,);
printf ( 'Yod', ilnuml) ; ,or(j= 0i j<= ,
j++)
i++ i pdntf('yod .,stud[m);
)
l
)
)

The output ofthe program would look like this: Look ar rhe pritrtf( ) statemelt...

printf ( 'Yod ', studlr[l j


addrcss=400'f elerrefi.=z4 24 24 24 )
address = 4003 elemeot = 34 3}1 34 34
address = 4005 ehrnefi= 12 12 12 12 fie trIsr is row nunber. The second
subscripr
address = 4007 element = il4 '14 '14 44
11,
EuDscnpl "+lltt{]
te s wbich ofthe two colurDtrs arE we talking about...
c9tryn or_the frst colum- thi
address = 4009 element = 56 56 56 56 Rem€mber tfr"i".rrti'og oi
11oth
address = 4011 *n,e,rt= 17 17 17 17 mws and columns begins witb zem.

Thc complete array arrangerneat is sho*n hlour


More Than One Dimension
dimensio[ It is also
So far we have looked at arrays with only one
possible for arrays to have two or more dimensions The two;
Chapter 2: Pointers and Arralts 55
54 lJnderstanding Pointers In C

oan be thought of as setting up a ooe-di!0€osiotral array of 5


elsments, each of which is a onedimeDsional array 2 eleme s
lorlg. We ref€r to an element ofa onedimeasional aray usiog a
iingle subscript. Similarly, if we oatr imagirc Eaud !o be a ore-
dimensional array then we can rcfer to its zeroth element as
stud[0], the next elsment as EtudEl ard so on. Mo!€;speci6cally,
if we execute the stal€ment

printf ( '0.6u", studlo] )


Figure 2.3 ;

'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, )

' int stud[51t2] ;


And here is the output...
Address of 0 th l-D aray = 4001
56 Undersnnding Pointers In C

'(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

6ffissions referio the

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.

pdnt ( i;t q[ ][4], int Dw int col ]


{
inti,ji 4001 4003 4005 4007 4OO9 40tt 4Ot3 4Ot5 4Ot7 4}tg 4O2t 4021

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.
)

1234 ln the show( ) function we have defined q to be a pointer to an


5678 lnay of 4 integers through the declaratiorx
9016
62 (Jnderstanding Poinlers In C
Chapter 2: Pointers and Atays 63

int (.q )lal ;


{2,3}
),
To begin with, q irolds the base address of the zercth l-D array,
{
i.e. 4O0l (rcfer Figure 2.4). This addrcss is then assigned to p, an (8,e)'
int pointer, and then using lhis pohter all elements ofthe zercth I - 17,21,
D alay are accessed. Next time thrcugh the loop when i takes a { 3.1},
value lf th€ exprdssion q + i fetches the address of tho first l-D {5,1}
array. This is because, q is a pointq to zercth 1-D anay and )
addilg I to it woutd give us the addEss ofthe next l-D alray. This );
address is once again assigned to p, and using it all elements of the
next l-D aray arc accessed. Here a is a 3-dimensonal array- A 3-D array can be thought of as
an array of arrays of airays. The ouler allay has three elements,
In the third tunction print( ), the declaration ofq looks like this: each of whicb is a twodimensional aray of four rows. each of
which is a one-dimemional array oftwo elemehts. In other words,
intqll[4]: a onedimeosiona!_array oftwo eleDents is constructed first. Then
four such ooe-dimeisional arrays are placed one below the other to
This is same as int ( rq )[4], vhere q is pointsr to an array of 4 give a two-diDensional aray containing four rows. Then. three
irltegefi. The only advantage is that we can rrow use the more such two{imeDsioD4 arays are placed ore behind the other to
familiar exEession q[il [] to acce$s array eleEreflts. We could have leld a theedidensional aray containing three 2-dimensional
used the sarne expEs$ion in show( ) as well. arrays. In the array declaratioo note how the commas have been
given. Following figune would possibty help you in visualising the
Three Dimensional Arrays situation better.

Consider the following array declaration:

int a[3]l4ll2l = xd 2-D Alray


{
{ tn 2-D kr.y
12,41, on 2-D Array
{7,8 },
i3' 4 ).
i5,6 )
),
{
{7,6 },
i3,4 ),
i5,3 ), Figure 2.5
64 Understanding Pointen In C

Again remember that the arangement shown above is only


conoepfually true. In memory the sauE aIlay elemeats arc storcd
linearly as shour in the follorring figure. {2,2},
12.31,
{3,4}
];
printf ("\n%u", a);
printf ( '\nolou', .a ) ;
printf ( 'b%u', -a ) ;.
pdntf ( lno/od', *a
) ;
Figure 2.6 printf('ho/ou',a+1);

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') ;

retuming a 3-D array. )

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

pnnf{'ln'); int (.fun30 )lROltlFOLl


){
int i, j, k;
retum (int')a; static int clSETllRoWllC0[]= {
)(
9.4. 6. 4,
)ICOLI
int ( 'fun2{ ) 1,3,2,1,
{ 7, 5, 1,6
inti,j,k; ),
static int blSErllROWllCOLI= { t
{ 6,3, e, 1,
9,4,6' 4, '2,1,5,7,
1,3,2,1, 4, 1, 1,6
7, 5, 1,6 )
), );
{
6, 3, 9, I , printr ( lnAmy cl l[ l[ I in tun3( ):\n' ):
2,1,5,7, for(i=0;i<SEl;i+t)
4, 1, 1,6 {
) for (j = 0 ;j < ROw; j++ )
); {
for(k=0;k<COL;k++)
printr ('\nArEy b[][][in tun2( ):h'); pinf('%d', clilU ][k]);
for(i=0:i<SET;i+I)
( prnrf{ln');
lor {j= 0;j< ROW;i++) }
(
)
lor ( k = 0 ; k < COL; k+I printf('\n'):
bti[i]lkl];
printf ( '%d ', )
pdntf('\n');
] retum ( int (.)lRotrt4lcotl ] c ;

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

pdnd(tu"); Anayb[][][jin main( ):


) 9464
'1321
printf('Vr'); 7516
)
6391
return ( int (t )lSEIllROWlcoLl ) d ; 2't 57
) 4116

And n"ere is the output... Anayc[]ll[]in tun30: ,

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];
)

if lqoinldent's marks for(i=Q;ifn;i++)


Such a aleclaEtion would typically be used
were to +e stored itr memory. The moment we make this
scanf ( "96d', (p+ i));
declaration 200 bytes aIe rcseped in memory for stoling 100 for(i=.0ii<nii++)
integers in il HowEver, it may so happen that when v/e actually sum:sum+.(p+i);
run thd program. we might be inteEsted in storing only 60
student's marks- Even in this case 200 bytes would 8et reserved in avg=sum/o;
memory, which would result in wastage of memory. printf ( "A .......ge mafts
=%d',
aW ) ;
86 Chapter 2: Pointe$ and Arrq)s gZ

,Here, we havefiIs! asked- for the number of studelEwhose-4alks Solved Problems


are tgbe eltqed-ard lhelalloqated 9ub/-"1-qt!ch rnemory as is
e 4arks. Not a byte more, not a b,'te will
IAI What be the ouFut oflhe following progiams:

(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)

i k have b€en declared as pointer vafiables, wbich would


atrd
n gives the address of the zeroth element, tr + I gives the
contain the addx€sses of foats. In otler words. j and k are
address ofthe next el€rtre ofthe array, atrd so on. Thus, n +
24 would give the address-ofthe last elemetrt ofthe array, and
Iloat poinlefs. To b€gitr with, the base addrcss of the array
therefore *( n + 24 ) wonld give the value at this ;itdress,
al I is stored io j. The ner(t statement is perfectly acceprablel
which is 200tu our case. Similady, *( n + 0 ) would give 100
flr. offte 46 trort fiom lhe base addrEss is storcd in
"aaress and the addition of the two *,ould result hto 300, \trhich is
k. The next t$'o stat€rne s arc €rroneous. Thrs is because the
outputted nexl
only operations lhat can be performed oa pointers are addition
and subtaction Multiplication or division of a pointer is IIot (4) main( )
allowed. Hence lhe error message.
{
int b[] = { 10, 20, 30, 40, s0 };
(3) main0
int i, 'k;
{ k =&b141-4; .
for(i=0;i<=4;i++)
nlol = 100 ;
{
nl24l = m0; pnntf ( 'Yod ', 'i( )
pnnf (t%d 96d',
-n,'( n + 24 ) +'( n+ 0 )) ;
;
k++;
)
90 Understtnding Pointers In C Chapter 2: Poinlerc and Arrays 91

{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

Mentioning the trame of an array yields its base address.


Hence, arr would give 1200. Since the aray contains flve Outpat
elemetrts. each of2 bytes, sizr ofthe array is reponed as l0
bltes. Note thal except when used with sizeof( ), name of the 65480 65496
array yields its base address.

(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

{ Therefore, the expressior used in the for loop, *( a + i ; = a111


int a[]= { 2,4,6,8, 10 }; + ilal is nothing but alil - alil + alil- Thus all that is done in
int ij the for loop is, each aray element is doubled and theD printed
for(i=0;i<=4;i+t)
out through printfo.
{
'(a+i)=a[]+ilal'
printf('%d',t(i+a))j (13) main0
) t
) int alsl = { 2, 4, 6, 8, '10 };
int i, b= 5;
Output
for(i=0;i<5;i++)
4812 1620 {
f (alil, &b ) ;
pdntl { 'h%d 96d', a0. b ) ;
Explatation
)
)
Imbibe the following three frcts and the program becomes
very simple to undeistaud: f (int x, inl -y )
{
- Mentio ng the name of the array gives the base address x=*(y)+=2;
oI the array. )
- AIIay elements arc stored in coDtiguous memory
localions. Output
- On adding I to the address of an integer, we get the
address ofthe next i[teger. 27
Wilh rhose factrs clearly laid out- let us oow try to undeNtand 49
the program. Remember that infemally C always acoesses 6 11
an:ay elements usi[g pointers. Thus, when we say a[i], 813
10 15
intemally C converts it to *( a + i ), which means value of iah
integer from the base address. Now, if tbe expression alil is
same as *( r + i ) then *( i + a ) must be same as i[al. But *( a llxpldhaaon
+ i ) is same as *( i + . ). Therefore a[il must be same as i[al.
After initialising the array when the control enteN the for
Thus a[i]. *( a + i ), *( i + a ] and ilal refer to rhe same loop, the fimction f( ) gets called with value of a[i] and
element lbe ih element from the base address. addrcss of b. In f( ) these are colleoted in vadables x and y.
Then comes the exptession r = *( y ) +- 2. Here *( y ) += 2 is
98 Understanding Pointers In C Chapter 2: Pointers and Arrays 99

evaluated fiIst and thell the Esult of this expression is 'b='b+1;


assigned to x. The first time thmugh the for loop
*( y ) gives b++;ri
5, to which 2 is added and lhe result is storcd at *( y ). It )
means 7 is assigDed lo b. Finally, the = operator 'assigns 7 to )
x. However, on assrgning a new value to x, the array element
alol in iDain( ) remai[s uncha[ged. Thus, du.ing every call to Output
f( ), b's value keeps getting updated, whereas therc is no
change iD the values of the array elemenh. 76543
Explsnation

E
401 b

l-5 I atol alll al21 a13 441


4008

4co2 4004 4M ,1008 4010

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

address of the next iateger, i.e. 6008. This prccess cotrtinues


(15) mainO till all the array elements have beea prioM.
{
int arll= {0, 1,2,3,4 };
int,pb;
for ( ptr = &ar{01 ; pt <= &ant4l ; ptr++ ) arrl0l arrlll alll2l .Irl3l arltll
tpr
printf ( '%d ', ); 0 I , 3 4
)
6008 6010 6012

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

The following figul€ would help in understanding the t


program. int an[]= {0, 1,2,3,4};
int'pt;
for ( ptr = an+4;pt'>=ar; ptr- )

arrtol al'0l ard2l ad31 aq[a] pdntf ( 'ol'd ', 'pf ) ;

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

Dts PE 60M 6006 6m8 6010 6012


Il-l rorz I PE-- -l eoro I
Figure 2.15

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

for ( ptr = ar + ar ph- )


4 ; p&>=
Possibly an easier way of understanditrg the expression ptr -
. pdntf('%d ', ar Ipr- ar]]; arr would be as follows. Suppose ptr coniains 6012 and arr
)
contains 6004. We can thell view the subtraction as ( rrr + 4 -
arr ), since ph is nothing but .rr. + 4. Nol^. I suppose its quite
Output
logical 10 expect the result ofthe subtraction as 4.
3210 (21) main0

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 ) ;

adoi arIlli anl2l alrt3] artal


Output
0 2 3 4

6006 6008 6010 6012 6004 0


9016 6004 0
9016 6004 0
Figue 2.16
E,Vlanation
Now things are getting really complicated, as the printf( )
would justify. Let us begin with the for loop. Firstly ptr is
assigtred the address 6012, the address of the fouth integer Look at the initiatisatior of, the array p[ l.
DuriDg
Aom the base address. Since this address is gre.ter than tie initialisafion, the addresses of various elemenis oi th" i
base addrcss, the condition is $alisfied and the control reaches ".r
a[] are stored in lhe aray p[ l. Sioce the array pl 1 contalns
pritrtf( ). What does rrr I ptr - arr I evaluate to? ptr - arf addresses of idegers, it has been declared as -ari
arrav of
means 6012 - 6004 which yields 4 and hence arr[4] prints pornters to integers. Figue 2.17 shows the conteats of arrays
out the fou h element ofthe array- Then ptr- reduces ptr to a[ ] and p-[l In the variable ptr, the base addrcss ofthe ariay
6010. Since 6010 is greater than the base address 6004, the p[ l, i.e- 9016 is storad. Since this address is the address of
condition is satisfied and once again the conhol reaches the p[0], which itselfis a pointer, pti has been declarcd as pointer
printf( ). This time ptr - {'r'becomes 6010 - 6004, i,e. 3. to an integerpoi[!er.
Thus arr[3] pdtrls out 3. This pmcess is repeated till all the
integeft ill the array have been p.inted out Let us undelstand the first pritrtf( ) rcw.
108 Unilerstaniling Pointers In C Chapter 2: Pointen and Anays 109

printf ( "hy"u %d', a, 'a ) ; Now onto tlle last printf( ).

pdntf ( '\n%u %u 96d', pr, *ph


It prhts out the base address ofthe array a[ ] and the lalue at 'pr, );
this base address.
Here ptr contains the base addiess ofthe array pl l, i.e. 9016;
*ptr would give lhe value at this addrcss, i.e. 6004; **ptr
would give the value at the ad&ess given by *ptr, i.e. value at
a[0] atll al2\ 431 {al address 60M, which is 0.
0 2 3
(22) maino
6004 6006 6008 6010 6012
{
p[01 ptu pql pt31 pt4l static intalt = {0, 1,2,3,4 };
sbtic int'pU = {a a + 1, a +2,a+3,a+ 4};
60M 6006 6008 6010 6012
*Ptr
9016 9018 90m 9022 int = P'
prr ptr++j a}
pirfff ( '\n96d 96d j6d', pr - p, -pr - a, *pb ;'
lg0'61 )

7888
'Ptr++'
printf ( 1n9{d %d 96d', pr - p, 'p[ - a, 'p[ ) ;

Figure 2.17 l++ptr;

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

work and increfienls value in ph to 9020. Now with ptr


Figure 2.18 would go a loag way in helping us to understand containing 9020, let us once again analyse the expressions ptr
this prograno- - p,*ptr - a and **plr'- .-
Herc ph has beetr declared as a pointer to an integer pointer
and assigoed-t[e base address of the array pt ]. which has altl at2\ at3l al41
401
been declared as an array of integer pointers. wllat happens
when ptr+ gets executed? ptr 0 I 2 3 4
lgiots ro the next inGger
pornter rp the armv pll. b other words. now 6010
btr adfiIdin. tfia- 6004 6006 6008 6012
adclress 9(r18. Now let us analyse the meaning ofplr _ p. *ptr
- a and r*ptr. ptol ptll pt3l pt4l
Pl21

pk-p 6004 6006 6m8 6010 6012

9016 9018 9020 9022 9024


Since ptr is contaiDing the address 9018, we can as \ ell sav (\
thal ptr is containing the addEss given by p + L t tren ptr - ptr ptr \l
I ,'*',ft"l
is reducedto ( p + 1 - p), which yields l.
i
tptr
f noro
7888.
I
- a 7888

*ptr pts ptr


means yalue at the address coatained in ptr. Since ptr
contairs 9018, the value at this address would be 6006. Now
6006 can be inaghed as ( r + t ). Tbus the e\pression
f,file"t-f,mtl
7888 7888
become,s ( a + 1-.), which is nothing but l.
PF pts
.**ro,l-eo2tl
llqo2o I
7888
ptr conlairs 9018, so *ptr yields 6006. and hence *+ptr
becomes *( 60116 which yields I
), - pE ptr

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

Sifoe ptr is contahing the adrlress 9018, we calt as v/ell say


401 ao1 al2l at3I
^L4l that ptr is contairfng the add.ess given by p + l. Thus ptr - p
0 I 2 1 4 is reduced to ( p+ l - p ), which yields l.
6004 6006 6008 6010 60t2
'ptr - a
ptol Dtu pI2\ p[3] pt4l
*ptrmeans value at the ad&ess contained in ph. Since ptr
600J ffit6 r)0O8 6010 60t2 contaiN 9018, the value at lhis addrEss would be 6006. Now
9016 9018 9020 9022 I I
6006 can tr€ imagined as ( + )- Thus the expression
becomes ( a + l - a ), which isnorhing tlirt t.
ptr pts
*.'*'-'
l- ,016 I f;;;-l *ptr

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 .

The [ext statement needs a closer took In *#*ph, the order


pts ptr
**rt,l- of evaluation would be *( ++( *par ) )- Sinc€ ph conlains
l- so18 I ror8 I a[2] is
changed to 3
9018; *( ptr ) would yield the value at 9018, i.e. 6006. Then
7888 78a8 ++ goes to work on 6{}06 and incrqneds it such that it is now
6008. Thus p[1] would now cortain 6008. And finally
*( 6008 would give 2, which
Figure 2-19 ) is ignored since it is not
assigned ro any variable.
Let us now analyse the expression **ptr+. ptr contains the
address 9016, therefore *ptr would leld the address 6004. Now, with ptr containing 9018, let us otrc€ again anall.se the
**ptr would give lhe value at this ad&ess- This value tums expressiotrs ptr - p, *ptr - a arrd *rpfu.
out to be 0. However, this r.alue is not assigned to any
vadable. Lastly ptr+ goes to work. This increments the ptr-p
value stored in ptr -to 9018- Once you are surc that ptr
contains 9018, let us oow proceed to fi[d out what the output
116 flnderstand.ing Pointers In C Chapter 2: Pointers and Arrays 117

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.

'pt-a Thus the output oflhe thi.d printf( ) is I 2 3.

*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

n[2]l2l prints out Se elcment io the second row atld second


column ofthe aaiay,
2 4 3 6 8 5 3 1

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

1. On incrementing ptrl it poitrts to the next location after


47
47 822, i.e. 824. ThereforE, next r'lme 6rough the for loop,
**ptrl gives value at 410 (which i8 obtained ttrougn *ptrfl,
47
i.e. 4. Similarly, last time through the loop, the value 7 geis
pdnted.
Explanalion
(28) maino
{
int t[3][2][4] = {
406 ,lO8 410 412 414 416 418 420
{
2,4,3,6,
ptstol PE[l] Ptt2I '1,6,7,9
q4 4t0 416 ),
{
a22 824 826 8,2,1,1,
2,3,7,3
prl ptrl
|-8;1 Prt*,f-E-l
),

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>:

char anll = 'Surpdsed' ;


char'ptr = 'Surprised' ;
126 127

No. Whenevq mentioning the array uame gives its base


address it is said that the array lus decayed into a pointer.
Explanatiot
This decaying doe$'t take place in tivo situations:

- 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?

(7) Would the following progam compile successfully? bqlanatiol


main0
( It decays into a pohter to an aray and trot a pointer to a
char a[ ] = "Sunst'oke' ' pointer.
char.P = "Coldwave' '
(ll)Are the three declaralions char **apple, char
*orangel l,
a = 'Coldwave' ;
P = 'Sunsfoke" ; and char cherryl l[ | same? <Yes/No>
pdntf { "\n9k %s', a, p ) ;
) Erplanatien
128 Chapter 2: Pointers and Arrays 129

No tun ( int (-ptr )I.[alu\COL] ) f ptr is pointer b an aray'/


{
(12) What would be rhe equivalent pointer expression for referring )
lhe element alilHlkllll?

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

printf ('\a%d',.( (int')p +4 ));


(14) How would you defire the tunction f( ) in the following
program?

int anl[rAXROlfl][MAXCOL] ;
fun ( ar);

Explana/io

fun ( inl a[ ]ruAxcoll ]


{
)
ti0 Understanding Pointers In C Chapter 2: PointenandAnays t3l
Exercise );
int'pfi[] = { a[0], a[1]. a[21 ] ;
int'pt2=pt,i;
IAI What will be rhe output ofthe follou,ing programs:

(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 ));

(2) main0 pdntf('ln');


(
for(i=0;i<=8;i++)
stailc i a[3][3]Bl = { printr ( '96d ', 'pb[ ) ;
(
1,2,X, ]
4, 5, 6,
maino
7,8,9
{
), adl= { 97, 98,99,
shlic int 100, 101, joz 103, 104 };
{ int'pk=ar+1;
2,4,6,
8, 10,12,
print ( ++pf, pt.-, pE ptr++. ++pf ] ;
14, 16, 18
)
),
{ pdnt ( int 'a, int'b, int'c, inl'd, int
.e
3,6,9, )
(
12,15,18,
printf (1n%d %d %d 96d 96d', -a,.b, t .d,.e
21,24,27 ) ;
I
)
); (4) majn0
static int 'Ptl I= {
al0l[0], at0lfl I, a[0][2], t
inr at3lpll2l = {
aFltol, al11l1l, atl1p1,
al2ll0l, aqlfil. a?lql {
1,2,
132 Understanding Pointers In. C

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.

What are Strings


The way a goupjlj4lECgqleg be s!ojd_!q_q!_!-ttr9g9l_9Iray,
similarly a group ofchamcters can be stoied in a character al y.
( hamcter aravs arc manv a time -also known as 'strinps Most
ianguag@t;nag, u"
134 {Jnderstanding Pointers In C Chapter 3: Pointers and Strings 135

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 )

4001 4002 4003 4004 '1005


4c[6 4007 4008 And hele is the output...

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

print out an array. This is because, prhtf( ) ftrctio! has got a


f Program 34 'i sweet and simple way of doing it, as shown below. Nott that
f Prcgram to pdnt sting demenb using pointer nobtion '/
printf( ) doesn't pdnt the .\0,.
main0
t,/ ' f Program 35 ./
fhar name11='16;61a|1'
maino
char'ptr;
{
ptr = name; f siore b6e addless oJ sting -/ char namell = 'Klinsman' '
printf ( 'ho/os'. name ) ;
-ptr != '10' )
while ( )
{ .pr The %s is,-a fognar
pnntl ( '%c', ); ryjfigatioo for priutjng out g qEilg_ The
same speclncaEon can be used to rcceive a string ftom rhe
Pf+|;
keyboard, as shown below.
)
)
I Program 36 'i
As with the integer aray, by mentiodng the name of the array we main0
set the base ad&€ss (addrEss qf the zemlb eleraq*>gf-the a!r.y {
fufrr*-arm*ffiA i, lte variable ptr using' char namel2sj ;

printf ( lnEnter your name: ' ;


ptr = name ; )
scanf ( '%s'. rlame t :

Once the base address is obtained in Ptr,


*ptr raould yield the printr (EEil6-yo-iF,-iame
) ;

value at this aditress, which g€ts pdrd Promptly thrcugh, )

printf ( 'o6c', 'pts) ;


And here is the outpt t

Enter your name: Debashish


Theq ptr ls incremented to point to the next chaIacter in thb Hello Debashishl
string. This deiv€s ftom twq factsl array elements are stored in
contiguous mernory locatiols and on incremerting a pointer it
Note that the decla.atioo ch.r mme[25] sets aside 25 charaoters
points to the innediately trext location ofits tJDe. This process is
under the arlay naEe[ l, whereas the scanf( funotion fills irt
canied out till ptr.gs!:t po-itrJtq-llbq-la!! Jharg9ler in the stli!9, ) the
characlers ryped ar keyboard into ttis-arsaFsSEE;;;GFB.r-
lPllsr\o', I!. Narurally. we should pass the base address ofthe arrav to the
scant( ) lunctlon.
Even though thcre are so many ways (as shown above) to refer to
the elements of cbaracter aray, rarely is any ore of them used to
138 Chapter 3: Pointers and Strings 139

on concalenation str'l = Bamboozledchap


Staldard Library String Functions
Note that itr the call to the fiinction strlen( ), we are passing the
C has a large set ofusefi
string handling library funciions. Here,
base address of the string, ald the function in tum retums the
we would illustrate the usage of most commonly usod functions Iength of the string. While calculatiry the length it doesn't count
(strlen( ), strcpy( ), strcar( ) and strcmp( )) through a program. '\0'. Can we not lrlite a ftoction xstrlen( ) I.hfch imitates the
staDdard library fiEctioD rhleD( )? Let us gi"la u oy...
f Program 37 '/
#include <sting.h>
main0
i' Program 38'/ ,/
main( )
{
sff {
char [20] = 'Bamboored' :
'ChaC '
char arl ]= 'Bambooy'ed' '
char stzll =
int lenl,len2;
char str3lml ;
int I, k;
lenl = xstden ( an ) ;
len2 = xstrlen ('Hum8Dunpty') ;
t=sUen(sH); printf ( lnsting = %s lerEth = 96d', ar, lenl ) ;
Pdntf ( 'hlerEth of stirE = %d', I ) i
printf ( '\nsting = %s leng$ = 96d', 'HumptyDumptf, bn2 ) ;

sucpy ( slr3, sbl ); )


printf ( '\nafter copying, sting str3 = %s', str3 ) ;
xstden (char's )

k = stGmp ( sfi, stz ) ;


{
stl intlength=0;
printf ( \on compaing and dr2, k = %d', k ) ;
while (.s != \0' l
k = strcmp (str3, slrt ) ; {
lenglh++;
printf ( lnon compadng st3 ard sM , k = %d', k ) ;

strcat ( sk1. st2 ) ; )


pintf ( '\non concatenation strl = 96s', si'1 ) ;
retum(length):
)
)
fhe output would be...
The outpul would be...
length ofsting = 10
string = Bamboozl€d length = 10
after copying, sting str3 = Barnbooy'ed
string = HumptyDumpty lenglh = 12
on comparing sH and st2, k = -1
on comparing str3 and sff!, k = 0
140 Undersanding Poinws In C Chapt* 3: Pointers and Strings 141

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

Pointers and Strings


strl ='Bye';FerDr'/
Suppose we wish to store 'Hello". We may either store it in a P = 'BYe" ; /' l'/otl(s'/

strillg or we may ask the C compiler to store it at some location in


memory and assign the addrcss ofthe string in a char pointer. This
is shown below:
The cazsl Qualifier
charstrl]= "Hello' '
char.p ='Hello"; The kewvord cotrst (for constant), if presenl- precedes lhe data
t}?e of a variable. It specifies that the value qftts:aeable-Ei[lot*
There is a subde dilference ia usage of these two foms. For cha4g9$Ilugborll-&efietf.f,t Any atlempl to alter lhe value of
examole- we cannot assisn a shins to aDother- wheteas. we can rhe variable defined wi$ this qualifier will result into an error
assign a char pointer to tuolher char pointer. This is shown in the message ftom compiler. cotrst is usually used to rcplace #delined
following progam. constants.

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

const is a better idea a$ codpared to #defirc because its scope of


.s=,K;
operation can lF controlled by placinq it appN'priately ejrher inside
a fiuction or oufside aI filnctiotrs- If a colglilplgqlin5ide a This would change the sourc€ saing to ':Kagpur'- CaIr we not
tunc@reas,ifit ensure lhat the source Sing doesn't change eveD acaidentally in
is placed outside "U f&€6on&$+its efect would be global. We xstrcpy( P We ca4 b/ chatrging the plotoq/pe ofthe fuirction to
cannot exercis€ such finfi control wtile usiDg a #deline
void xstrcpy ( chai onsl chal. ) ;
crrs, Pointers
Corespondingly the definitiotr \r,ould change to:
Look at the followhg program:
void xstrcov ( char't. mns{ char t }
f Pw.an 42'l {
main( )
f code '/
{
)
char sH[]= 'Nagpul '
charsr2{101;
The following code fragrned would help you io fix your ideas
about cotrlt further.
xstrcpy ( str2, sfi ) ;
printf ( 1n%s", st2 ) ; char'p = t *'* "11s110' b yaiaile, so b sfring '/
.P='M';fuo*s'/"
)
P='BYe"jl'orks'/
xstrcpy (chart, dEr's )
{t/ while (
.t != 1S
qonst char'q = 'Hello' '
'q='M';lenor'/
f $ing b corEbrt Finter b nd 1
)
{
q = "BYe' if wo s'/
ts
t*. char const = 'Hello' ; F sting b corEtant pointer is mt '/
s#; 's = 'l\.,|' ; f ercr'/
)
s = 'Bye" ;f wofts'/
*t
= 10' ;
)
*
char const t ='Hello'; f poinbr b colEbot sfiing b mt'/

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;
)

Here since the fimction fun( ) is retmring a constant string, we


printf ( 'hhter your namq ' );
('%s', youmane ) ;
cannot use the pointer p to modi& it Not only this, the follov.ing
scanf

operatiotrs loo would be iDvalid:


flag = 11916Or*, '
(a) main( ) canngt assign the ietum value to a pointer to a non-
for(i=0;i<=5;i++)
cotrst stri0g. {
a = strcmp ( &m6blflsu[0], pumame ) ;

O) main( cannot @ss the Ietrm value to a fimction that is


) {
expectiog a pointer to a tron-const string. printf ( "Welcome, you can ent€r he pala6e' ) ;
flag = Pgg*'
Two I)imensioual Array of Characters break; '
)
In the previous chaptfi we saw seveml examples of 2_D trumeric )
arays. Let's now look at a similar phelomenon, but one dealing
with chamcters. The b€st way to urde6tand this cotrcept is through if ( flag == ll6lPgg^t,
printl ( "Sorry, you are a tespassef ) ;
148 Ufldersto ding Pointers In C Chapler 3: Pointen and Strings 149

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

Enter your name raman


Welcome, you can enbr t|e palace Figure 3.2

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 ) ;

|rray of Pointers to Strings


While comparing the strings through strcmp( ), nore that the
addrcsses of the strings are being passed io strcmp( ). As seen in As we know, a poitrtq variable always oontains an addrpss.
the last section, ifthe two strings match, strcmp( ) would retum a Therefore, if we colstuct a array ofpointers it would cofiaitr a
value 0, otherwise it would ietum a non-zero value.' nirmber of addresses. I,€t us see how the mm€s itr the earlier
example can be storcd in lhe array ofpoiDters.
The variaile flag is used to keep a record of whether the control
did reach inside the if or not. To begin with, we set this flag to ch'namesl]={
NOTFOLIND. Later through the loop if the names match this flag 'akshay';
paras"
is set to FOUND- When the control reaches beyond the for loop, if 'raman',
flag is still set to NOTFOUND, it means none ofthe names in the
maste:llllllll<tched with the one supplied from the keyboard. 'sdnhr6',
'gopd,
The names would be stored in memory as shown in Figure 3.2.
Note that each string e[ds with a '\0'. The arrangement as you can ); "ajesh'
appreciate is similar to that ofa two-dimensional numeric aray.
150 Understanding Pointers In C Chapter 3: Pointers and Strings t51

In this declaration nam€s[ | is aD array ofpoidtsrs. It contains base f Program 45 '/


addresses ofiespective names. That is, base addresses of "akshay" m-ain( )

is stored in lrrmes[0], base addr€ss€s of "parag" is stoied in {


namesu and so on. This is depioted in the following figure. char 'namesl ] = {
'a|rshall,
'parag',
'raman',
I"Lhry\ol Trr.,"\o I I ".1,,i-r-\ol 'srinivas',
'gopaf,
r0M 1(x8 2006
'rajesh'

fs"p,r\ol l-"j"h\o I fe-"sql l;


char'temD i
4008 60/}2 7118
printf ( \Oiginal: %s 9Ls', nantes[2], namesp] );
naEes[ ] temp = names[2] ;
lm4 7ll8 l(x8 2006 4008 6002 namesl2l = namespl :
namespl= lemp :
8112 8r14 8116 8lt8 8120 8122
pdntf("\nNew:%s %s', nan€6[2], mrnespl ) ;
]
Figue 3.3
And here is the output...
In the two-alimensional axray of characters, the strings were
ocaupying a total of 60 bJ.tes. As asaiNt this by using the array of Original: raman srinivas
pointers to stings ihe same shings can now be stoEd usfurg only New: sdnivas ramam
53 bytes, 41 bytes for l e actral sairyE ard 12 for the array of
poiotets. A substa i4l saving that go€s on increasitrg with the ln this progmm all that we are rEquircd io do is exchange the
oumber ofnames being stored. addresses of the names stolgl;g]Bg arraJjlt-pqitlEls, rather.than
the EfrEFIRAiselGs:Th_lrs" bv effectins illct onei-E&hatrge
erchanse we are
Thus, one rcaso4lqslore slrisgs-i! an array of pohtel$ is to make able to interchange name_!r. This Eak€s rnamgiry strings very
moFeffi @L]E9lrtavailahle-gleEory. convenlenl.

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.

(4) mdin0 (5) main()


{ {
char stl I = { 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 } ; charstr'lll='Hello''
char's ; char stz[ ] = 'Hello' ;
int i; if ( strl == str2 )
s = str : pnnf('inEqual');
for(i=0;i<=9;i+}) else
{ pnnf{\lunequal');
if(\) )
pnntf ( '%c', 's );
Ourput
)
) Unequal

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

) We know that exp.€ssion r[,ll gets converted to *( a + 4 ),


where a gives the base address of the array. On similar linos
Ou.tprt n.bcdefghn[,{ becomes r( tr.bcdtfghn + 4 this is same as
).
*( base iddress + 4 ( brse .ddrct! + 4 ) yields address of
).
No output 'e'. Thus, what gets pass€d to pff(
) is the chaBctel 'e','
wbich is promptly prhled ouL
Explanation
(8) main( )

Though you may not have expected zerces to be outputted {


char sfm = 'Stings' ;
this time, you surely did exp€ct some output! We stored the pdnf ( '96s', sfr ) ;
character ooresponding to ASCII 0 fu all 10 eleme s of the
)
string. Nex! w€ assign s, a char pohter, the base ad<lress of
the string. Through fhe for loop, we arc atternptiog to prht
out all eleEents one by one, but not before imposiug the if Output
condition.
Cannot predict.
The if is made to test the value at addrcss cootained in s
ofprintf( ). First time through the loop,
before the execution
*s yields ASCII 0. Therefore lhe lf statemert reduces to Explanatial
if hlsity, the cohdition ftils. Hence, s
( 0 ), and as 0 stads for
is incremented aDd coDhol loops back to for without Herc str[ ] has beetr declarcd as a 7 chaiacter aray and into it
execuling the prfutf( ). The same thing happeN the next time
around, and the nex! and so on, till the for loop ends, I
a character striry has beeo stoted. This v,.ould result into
resulting in no ouout at all.
overwriting of the bye beyond the rcventh byte reseNed for
the array 1,ith a '\0'. Th€re is always a possibility that
(7) mainO
something irlpofiant gets overwri$ea, wiich would be unsafe.
{ (e)
pnntf ( 'yoc', 'abcdeEh'[4] ) main0
:
{ tsE[
char I = { 'FrogE , 'Ib', 'ilctr, 'IIe.', 'nlef, "Crcak!' } ;
pdntf ( '96d 96d', dzeof ( sfr ), sizeof ( stlol ) ) ;
OutWt
)
160 Undersnnding Pointers In C
Chapter 3: Pointen and Strings 161

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.

Since ! gives the base address of the array, ( s + 5 ) would


give the .ddress of the fifth element from the bas€ addxess.
162 Understanding Pointers In C Chapter i: Pointers and Strings l6j
This address is pass€d to the s€ootrd printf( ) Using the arc rcferring to tle base add&ss ofthe string. This is the only
formal sp€cification yos, the co ents ofthe string are printed Ltformation lhat helps the C conpiler keep track of the string
out the 5d eleinem oowards. arrl l. If this hfomation is los! there is oo way the oompiler
can acoess the striog. So, this particular address is given a
The fiird prin( ) priDls lhe etrhre stsing as the base address favoured stahrs, that of a constant. The statement arr.+ is
ofthe saing is being passed to it. essstrtially wrong because a constant oa!'t be incrcmented
and hetroe the compilel asks for an Lvalue, which is a value
The fourth print( ) is made to print the second character of that can be ohanged.
the striog, as *( s + 2 ) is oothitrg but s[2] Thus '['
gets
printed. (13) main0
{
Does the output of lte 6nal pritrtf( ) suprise you by printiDg charst{l = 'Limeicks' -

out a number, 4(N? Note that the format sp€cifioation you is


*s
char ;
used \i/ith s, which gives lhe base address of the saing. It s=&stl6l-6;
happercd to be 404 when we executed lhe proglaltL whioh go1 while ('s )
printed out. On executiDg the same yourself, you rray get any Pdntf ( "%c', 's++ ) ;
other addr€ss, depending oa what addEss is allotted to the )
strilg by the cotrryiler
Outp t
(12) main( )
( Limedcls
char ar{ I = 'PtolQocleliru my peace ol mind..'
inti; Explanation
pdntf ( \%f, 'ar );
an+;
pdntl ( '\n%c', -arr ) ;
The following figqr€ would help ir analyzing this program.

Output

Enor mesrage: Lvalue rcquiEd in furrcIion main

Explarratio

Though everything seems to be in order at first glance, thele


lies a fundamedal error irl oua pfogiam. When lve say arrr we
164 Chapter j: Pointers and Strings 165

'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];
)

l-4oo{j11-f 4oorl Oatput

cone

Figue 3.4 ase


Ieen
s has been declarcd as a pohter to a ch.r, whereas str[ ] has
besn declaEd as a chardcter strilg. Let us Bow evaluate the Explanation
expressior &str[6] - 6. Here &str[6] gives the addrcss of the
sixth eleme* ofthe string. This address oan also be obtained This time we seem to be faced with a galaxy of sta$! We
by the expression sh + 6. On subtractfurg 6 from this, we,end would do well to take rhe help of a figure iu orossing them
up v/ith good old str, th€ address ofthe zeroth element, which
one by one. At the outset, s[ I has been declared alrd
is assigaed m r.
initialised as an array ofpoidters. Simply salng r gives us the
base ad<lress of this array, ,()06 as can be seea Aom Figure
In the prhtf( ), lhe valuc at addrcss cotrtaired in s is printed,
3.5. ptrl ] storcs the addre$s€s ofthe locations wh6e the base
and then s gpt$ incr€mented so that it poitrts to the next
ad&esses ofstrings comprising s[ J have been stored, starting
character in the sting. The while loop conti[ue8 till I doe$r't
with the last string. To put it more clearly, ptr[o] stores the
point to '\0', vhich ma*s the eDd ofthe stritg. Wheo r points
address 4012, vhich is the address at which base a{&ess of
to '\0', the value of i3 would be 0, a falsity. Helrce the whlle
the string "please" is stored. Similarly, ptr[l] stores the
loop will be terminated"
ad&ess 4010, which is where the base address of the string
(14) main0
"cone" is store4 and so on. Sirce ptrl I essentially stores
addresses of addresses, each olemetrt of it is a pointer to a
t pointer. aDd has been declared as such usirg **.
static char's[I= {
'ice',
'sl€€tl" Finally, the base addrcss ofpli[ I is assigned to a pointer to a
. 'coIE, pointer to a pointer, p. R€€ling?! Going ttuough the figure
\
Chapter 3: Pointers and Strir,8.s 167

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

pttol pt{ll prrt2l ptr[3]


p, presetrfly co ains 6022, wldch m incremetrtitrg becomes
40t2 4010 4008 4006
6024. value at this ad&€ss is lhe addr€ss 4008, or in t€rms of
@20 @22 6026 B, s + l- On lhis 0!€ d€clem€[t q,€Btor --works.to giYe 4006,
i.e. s. Value at 4006, or r( t ) is 1000. Thus the bxpressiou is
now reduced to ( 1000 + 3 ), md a,nat finally gets passed to
P printf( ) is the addrcss 1003. Value at this address is a '\0', as
at the end ofevery sting a 'W' is ihs€rted automatically This
l- 6010 I '\0' is pritrted out as a blatrkby pfirq)-
.PL2l +
3
Figure 3.5
The cuneDt address itr p is 6{D4. 'Pl-2J can be thought ofas
Having soied out what i$ pres€nt wherc, we now proceed io *( *( p - 2 ) ), as ntrmlil is sme as r( rum + I ). This itr tum
the printf( )8. Let us taclde tlro expressioas one by ooe. evaluat€s as *{'(60A -2)\i.e. i( *( 6020 ) ), as p is a
pointer to a pointer. This is equal to r( 4012 ), as at 6020 the
"*+p address 4Ol2 is present. Value 8t /Ol2 is 1015, i.e. the base
address of the fourft strin& hlease"- Having reaohed the
The fust o!€ piitrts out the stiog statiog ftom the address address of letter 'p', 3 is adde4 which-rields the address
**J-lp. The -* goes to wort fiIst atrd increments p not to
1018. The string starting fiom 1ol8 is pdtrted out, {hich
6021, but to @22. 't\e C compiler has been made to comprises ofthe last thlee leltets of'please", i.e. 'ase'.
understand that on fucEmenting a pointer variable, it is to
168 Understatding Pointers In C 169

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.

(15) main( ) p+i<=str+stien(str)


{
char si4 I = 'For Your eyes onlf ' Since length Df str[ | is 18, str + shlcn ( str ) would give the
inti: address of '\0' present at the end of tlrc strhg. If we assume
char 'p i
that the base address of the string is 40O1,l en the address of
for( p = sf, i= 0:p +i<= st+stlen ( str) ; p++, i++ ,1019. Sincc p bas been assigned the base
pdnf('96c"-(p+i));
) '\0' would be
address of the sEing in the first go, p + 0 would leld 4001.
)
Sirce this is less than 4019, the condition holds good, and the
charaoter prcsent at the address ( p + 0 ), i.e. 'F', is printEd
Output out. This can be uodeGtood bett€f, with the aid of the Figue
1.6.
Fryu ysol<spac€>

After this, both p and t are ircEmqted, so that p colltains


Explanatioa 4002 and i coatains l, aod orce agaiu the conditior in the for
loop is tested. This time ( p + i ) yields 4003; whereas the
171
170 Ilnderstandtutg Poin ers In C

base address to be ul00l, the[ s would contair the address


€xDressio! + .hlm ( sh ) contilues to yield 4019
sf 4009, Since this address is greater than the base add&ss, filst
Thercfore, egaiD lhe coodidon is satisfied and the chamcter at time thmugh the loop the condition is:satisfied. Nsi-th€ value
address 4003, i.e- 'l'
gets printed. Likewise, alternate
of the expressioo *$ i$ prinred. Sinc€ s oontains the ad&€ss
elem€nts ofihe strhg arE ouEutted till i is 8, coresponding to
4009, the value al this addr€ss, i.e. 'M', gets p nted. Then s is
which f
is piated Nov, when p and i are incremcnted one
deGemented to point to the preceding elemeot, i,e. the
more 1ime, iha &st co litioo €valuates to: elernent at addi€ss 4008.

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

poi t€r to a ch.r, is assigned an address 8 locations ahead


s, a Mbbllee wwaass ll ee
of tie tase ad&Ess of 6€ saing. Tbat meals s is ourrently
poitrtiE to the last eleme 'M' ofthe string. Ifwe assume the Explatation
172 Understanding Pointers In C Chapter 3: Pointers and Strings t73

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 ) ) ;

This goes on till the end of the string s[ I is encountered )


which is marked by the presence of a '\0', havitrg ASCtr
value 0. When this character is stored in t[ l, *ta would give Outpu,
'\0'. This time when the coodition is tested, it evaluates to
176 Understanding Pointers InC Chapler 3: Pointers and Strings 177

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.

Outpttt (?3) main( )


{
ENTER NAME: Par4 char names[5][20] = {
You entered Parag 'Roshni',
178 [Jnderstanding Pointers In C Chapter 3: Pointers and. Strings 179

'Manish', (24) main( )


"Mona', {
"Baiju",
"Ritu"
'
char messlBl[3oJ = {
"Don\walk in frontofme ...',
); "l may nol follow;',
intii 'Don't walk behind me,.,",
char 't j 'lmay not lead ;",
t = names[3] ; 'Just walk beside me.,.',
namespl = names[4) i 'And be my ftiend."
namBs[4] = t; );
*(
for(i=0ii<=4ii++) prinlf( \o/oc %c', messl2l+ I ), '('( mess + 2 )+ I )) ;
pdntf (ln%s', nameslil) i )
)
Output
Output
kk
Enor messsgei Lvalue requiEd in function main
Explasaliort
ExplanatioL
The two-dimensional array comprises of one-dimensional
Apparently, what the program atiempts !o do i8 interchange arays, each of which is 30 characters loflg. We know,
the addresses stored in mmes[3] atrd DrDe"t[4] using atr messl2l[9] refe6 to the th element ofthe 2 l-D anay.
auxiliary variable t. SoundE straight fon*'ad, but is essertially
against the v€ry concept of how the C compiler d€a-ls wilh Recall Orat melsl2l would give the base address ofthe secord
strinss. The compiler keeps Fack of any string by string. If this addre3s turns out to be 4001, then the expression
remJmbering only tl,e base address of the string. So it has its mcsr[2] + 9 would become ( 4001 + 9 ), which would give the
reservations when it comes to chalgilg this infomation, as it address of the ninth charactq from the ad&ess 4001. This
anticiDates that there would be no one to blame bui itselfonce address happens to be the address ofthe letter'k' in the striog
this iiformation is waylaid and we dernand an aocess to the 'Doa't walk behind me". Hence this letter 'k' can be accessed
string laterl And this is what i$ beitrg attempted itr the by the expression *( mess[2] + 9 ). But we aheady know that
statement namesl3l = names[4]. Here we are trying to change whenever we use the notation mess[2], is intemally it
the base address storcd ilr namerl3l As said eadier, this will converted to *( mess + 2 ) by the compiler. Therefore
not be allowed. Thus the starting address of a stsing is afl *( m€ssl2l + 9 ) can also be expressed as *(*( mess + 2 + 9).
)
indelible entity, in no way aa Lvalue, which is a value that
can change, Hence lhe error message. Thus, mess[2][9], *( mess[2] +9)and*(*(mess+2 )+9)
are one and the same, i.e. the 96 element of the 2nd string in
180 Undersland@ Pointers In C Chapter 3: Pointers and Strings t81

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++;

No, since what is plgsent in memory beyond "United" is not )


known and we are attaching "Fro[t" at the end of "United", 't=10';
thereby overwriting something, which is an unsafe thing to )
do.
Erplanatiorl
(2) How would you improve the code in (2) above?
User-defined strcpy( )
Explahation
(4) Can you compaot the code of$trcpy( ) given in (3) above into
main( ) one line?
{
char str'1 [15] = 'United" ; Explanatiol
char'st2 ='Front';
*str3 ts
char ; strcpy ( char 1, char )
str3 = strcat (str1, st2 ) i
{
pdntf ( lno/os', str3 ) ;
vrhile(*t++='s++1;
)
182 Unders tanding Pointers In C Chapter 3: Pointers. and Strings 183

) oao be changcd but the ad&ess of the array would rernain


same.
'(5) How would you futd the lenglh of each sting in the program
[A](9) above? Ou Oe other hand, p is a poitrtEr, itritializcd to point io a string
coNtant. The pohter p ltray be modified to point to another
Explonqlion shin& but if you sttempt to modiry the sting at which p is
poitrting the Gsult is undefined.
maln0
( (8) While handling a stsing do we always have to prccess it
char 5r[ ] = {'Frcgs', 'Do', 'Nof, 'DiE.', 5hefr, "Cmatl' } ; olDtaotgr by character or ther€ cxisb a m€thod to processltha
lntl; entir€ sting a! one udt.

tor(l= ();i<= 5; l++ ) Eqiluatioa


pdntf ( 1n%s %d', 6tr[, sfi€n ( $nl )) ;

)
A 8thg car bc proc€8sed ody o! 8
(6) Would the foltowing code oompilc sucoessfully? basis.

maln( )
{
printf ('%c', 7l'Sundaram" I ) ;

Explanaliofl

Yes. It would print 'm' of "Suudaram".

0) What is the diff€rence in the followiry declarations?

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

Write a Eogram to arange these ,rames in llphabetical order.


Exercise
(4) Wdte a progmm to compress my given string such that the
IAI Attempt the following:
multiple blanks prcsent irl it arc eliminated. Store the
(l) Wdte a furction xstrchr( ) which scans a string from compEssed message io anot er sting. Also write a
beginning to end in search of a character. If the character is decoinpressaat program to ggt bock the odginal string with all
found it should retum a pointer to the first occurrence of the its spaces restored.
giyerr character in the stillg. If the given characler is not
The uncompressed string can be:
foirnd in the string, the fiDction $hould retum a NULL. The
prototypc ofthe function would be: 'lmpeidPalace. Rome. Attenlion Julius Caesar. oear Caesar, u/e
have the clariication you EquesM. Details lo follow by courier.
char ' )6trchr ( char'sting, char ch ) :
Mean$rhile stay clearol Brutus.'
(2) Write a function xstrsar( ) that will scan a stsing for the
(s) Write a program to encode any given string such that it g€ts
ooculronce of a given sub-string. The prototype of the
convet€d into an unrecognizable form. Also write a decode
furlctiofl ]r,ould be:
function to get back thc original string, Try to make the
char ' xstrctr ( char 'stdngl , char'sting2 ) ; encr,?tion soheme as difficult to brcak as possible.

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

static char su2[20] ; . while ( 'tt )


slatic char sr3Pol = 'Daf ' {
intl; if(('uu++='tt++)==")
brcak;
|= stcmp ( stcal ( st3, $rpy ( st4, sH ) ), stcat ( )
sr3,'Sood')); )
pdntf(%d',1); 'uu=\0;
I puts(u);
)
(3) main0
{ main( )
char slr Il = 'Way oftDubl€ Is out hDugh it' ; {
inti; char a[2][2][25] = {
{
br(i' 0;i<.3 ii++ ) 'Jack and Jill',
pdnf('Ybc','( st + i) )i "Went up the hill"
for(i=0;i<=3;i++) ),
Pdntf ('%o','(sf + 18 + i ) ) i (
for(i=0;l<=13;i+t) 'Jack felldown",
('96c','(sf +4 + I ) ) ;
printf "And bloke hh crown'
for{i=0;l<=9:i++) )
p ntf ('96c','( sr+ 22 + i ) ) ; )i
) pdntf ( 'b%s %s %s %s', &atollollgl, &al0l[1][12],
&a[1]l0ll10l, &allll1lllal ) ;
(4) main( ) )
{
chars[]='Caof''
char ttl = 'is Phil6ophy lib' '
char u[40] ;
char'ss I s,
rt ruu
= t. =u ;

.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.

Qointers anf S tractures

ile handling real world data, we usually deal with a


colleciion of itrts, chars and floats rather than isolated
entities. For example, an gntity we call a 'book' is a
collection of things like a title, an author, a call number, a
publisher, number ofpages, date of publication, price, etc. As you
can see, all this data is dissimilar; authoi is a string, prioe is a lloat,
whereas number. of page$ is an int. For dealing with such
c.olleotions, C provides a data type oalled 'structure'. A structure
gathers together different atoms of infomation that folm a given
edity.

Look at rhe following progEm that combines dissimila! dara types


inlo an entity called shucture.

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)

printf("\nolod o/os 0/0f',


An Array of Structures
a1,no, a1.acc_name, al.bal);
printf('\no/od o/os
%f', a2.no, a2,a6c_name, a2.bal); In the above example ifwe were to stole data of 100 accounts, we
pintf('\n%d %s %f', a3,no, a3.acc_name, a3,bal); would be rcquired to use 100 differeflt shucture variables ftom al
) to 4100, which is definit€ly not very convenient, A better approach
would be to use an aEay of stuctures. The arangement of the
Now a few tips about the programl
atray of strucrures in memory is shown in the following figure.
(a) The declaration at the beginning of the program combines
dissimilar data tlpes into a single entity call€d struct
account. Here struct is a ke),\trord, account is th€ stucture alo].rc a[o].bal alll.no alll.bal a[g].no a[g].bal.
name, and the dissimila! data types are stucture elements. 134 4892.30 t22 6432.90
007 2000.55
(b) al, a2 and 13 are structure variables of the q?e struct
accoutrt. ,1000 4002 4006 4008 4054 4056
(c) The structwe elements arc acoessed using a '.' operator. So to
refer no we use tl,no and to refer to acc tr&me we use
al.rcc_name. Before lhe dol there must alwayi be a structure Figwe 4.2 Aray of structures in memory
variable and after the dot there must always be a shucturc
element.
Now let us write a Fogram, which puts the array of struotules to
(d) Since a1.!cc_name is a string, its work.
base addrcs$ can be
obtained just by mentioning al.acc_name. Hence the .addrEss ./
of operator & has been dropped while receiving the account f ftoglam 49
main( )
name in scanf( ).
(
(e) The shucture elements are always arranged in contiguous
slruc{ account
memory locations. This arangemenl is shown in the
{
following figure.
192 Understanding Pointers In C
Chapter 4: Pointers and Structures 193

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 ) ;

for(i =0; i<= 9; i++ )


or even...
{
prinlf("\nEnter account no. and balance;, ); struct
scanf('%d %f', &ac6, &balance )j
:
alil.no = acc alij.bal= batance; {
char rEme[2o] ;
printf ("yod %f', alil.no, alil.bat);
int age ;
)
1
)p1 = ( "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,

More about Structures slrucl player


{
char name[2o]
Let us now explore the intricaoies of structures with a view of ;
int age ;
programming convefl ience.
);
stuct player p2, pl = { "Nick Yates', 30 } i
(a) The declaration of shucture t pe and the structute variable p2=pli
can be combined in one statement. For example,
(c) One structure can be nested within another strlrcture as shown
struct player below.
(
slruct part
char name[2o]j
int age;
{
char type ;
); int qty ;
struct player pl = {'Nick Yates', 30 } ;
);
struct vehicle
is same as
{
char marutl2o] ;
194 Understanding Pointers In C Chapter 4: Pointers and Structures 195

struct pad bolt i


I
); sfuct @ok b!.= { "Let us C", YPK", 101 } :
v;
struct vehicle
v,bolt.qty = 300; -${tq!]!il
I
pr= &bl ; /
(d) Like an ordinary variable, a structute variable can also b€ prin ( '96s yos o6dln', bl .name, bl .author, bl .callno ) i
passed to a function. We may either pass individual struch[e pfnf ( 16s %s o/odb', ptr -> name, ptr -> author, ptr -> callno ) i
elements or the entire structure at one go. If aeed be we can )
also pa8s addresscs of struoture el€ments or address of a
stluotu€ variable as shown below. The first prlrtf( ) is as usual. The second prlntf( ) however is
peculiar. We ca['t use ptr.nrme or ptr.c.llno because ptr i6 not a
stuot Player struch[e variable but a point€r to a structue, and the dot operator
( requir€s a stucturc variable on its left, ln such cases C proyid€s an
charnamt2ol; operator ->, aalled an arrow operator to refer to the shuoture
int age i
eleErents. Remembsl that on the left had sidc of the '.' shuotur€
); opsrator, theE mugt always b€ a stucture variablc, whereas on the
strucl player p1 = {'Nick Yatos , 30 } ;
I
display ( pl.nam, p1,age ) ; pEsing indivirud 6l6monb'/
left hand side ofthe -> operator thele must always be . pointer to a
show ( pl ) j passing sruduB valiabla'/
I stsucturc. The arrangement of the structue variable and pointer to
d ( pl,nam, &pl.age ) ; f
psssing addBss€s.of stuctuIo dem€nb'/ st uctuI€ in memory is showa in the ffgure given below.
print ( &p 1 j ) I
passing addr€ss of shtGtrs yadablo '/

Structure Pointers - bl.mmc bl.author bl.callno


IrtUsC I YPK ll01
The way we can have a pointer poitltiog to atr lut, or a Poht€f,
poilti[g to a char, similarly we oatr have a pointsr pointhg to a 4ml 4051

itruct" Such pointers ale knowtr as 'stuchlre pohters'. L€t us look


at a program, whioh demonstr.tes the usage oflhese pointers- ptr

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);
;

) In the funotion fun( ) call we access the elements of structure b


thrcugh the address ofz.y? We can. For this we need to first find
And here is the output. , out lhe ofhet ofJ. Using this offset we catr fiDd out ad&pss whele
r begins io memory. Once we get this address we oan have an
C
Let us access to elements i, f and ch. This is shown in the following
YPK pro8ram'
101
f prcgram 52 ./
Again, note that, to access the structure elements Dsi[g pointer to druct a a
slructure we have lo use the L>' operator. Also. the shucture {
struct book should be declared outside main( ) such that this data $ruct b
t)?e is available to display( ) while declaring the variable b as a {
pointer to the structure. int i ;
lloat f;
Offsets of Structure Elements )r,.n,t.n'
Consider the following stluctule:
198 Und*standing Pointers In C Chapter 4: Pointers and Structures 199

struct c strirctur€ mriable t, But sinoe fu(


) has been passed a pointer to
t structue c, we do trot have direct acoess to elements of x. The
inti; solution is to calculate the offset of the fiIst m€mber of y, in our
float g ; case, j. This has been achieved through the staternefl:
chai ch j
)Yl ofhet = ( char ' ) & (( struct c') (& ((slruct a ') O )-> y )-> j)
); (char-) (( slructa' ) 0 ) ;

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

In the above statement & ( p > j ) gives the addrcss of member j


of structue variable y. Subtracthg offse1 fiorn this yields the and the Next pad is a poi[ter to the next node. The NULL in the
Iast node indicates that this is the last [ode in the list.
addross of stuotule variable x. Using this address, lve have stoEd
the values in the member variables i, f and ch. Back inlo main( ),
There are several operations that we can think of performing on
we have printed these values using prtntf( ).
linked lists. The following pro$am shows how to build a linked
Iist by adding new nodes at the beginning, at the end or in the
Linked Lists middle of the linked list. It also contains a funotion disphy( )
which displays all the nodes present in the linked list and a
Linked Iist is a vbry common data structute often used to storc function deleae( ) which can delere any node in lhe linked list. co
similar data in memory, While the elements of an array occupy through the program carefully, a step at a time.
contiguous memory looations, those of a linked list are not
conshained to be stored in adjacent locations. The individual f Program 53 'i
elements are siored "somewhere" ill memory, rather like a family f Prcgram lo maintain a linked list'/
dispeNed, but still bound together, The order of the elements is #include 'alloc.h"
maintailed by explicit lirks between them. For instance, the marks
obtained by differeilt students car be stored in a linked tist as f $ructure containing a data part and link pad */
shown in Figure 4.5. struct node
(
int data ;
slruct node 'link i
Data Nctt )l
main0
{
stuct node *p ;
p = NULL ;f empty linked list:i

pdnf('hNo. of elements ln the Linked List: %d", count ( p ) ) ;


Figue 4.5 append(&p,1);
append(&p,2);
Observe that the linked list is a collection of elements called append(&p,3):
nodes, eaoh of whioh stores two items of infomation-an eleme( append(&p,4);
ofthe list and a link. A link is a poifter or an addrcss that indicates append ( &p, 17 ) ;
explicitly the location of the node containing the successot of lhe
list element. In Figue 4.5, the arows rcpresent the links. The cllsc( ) ;
Data pait of each oode cotrsists of the marks obtained by a student display ( p );
addalbeg (&p, 999 ) ;
202 Understanding Pointers In C Chapter 4: Pointer.s and Structures 203

addalbeg ( &p, 888


while (temp -> link != NULL )
addatbeg ( &p, 777
temp = 1sO -, 1;n* ,

display (p ) ; f add node at the end 'i


r= malloc ( sizeof( struct node )) ;

addaftor(p,7,0 )i a) data = num ;

addafter(p,2, 1); r) link = NULL ;

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 ;

lemp = malloc ( sizeof ( struct node ) ) ;


inti;
lemp "> data = num '
temp>link=NULL' temp=q;
'
-q=temp; f skip lo desked portion'/
tor ( i= 0; i< loc ; i+t )
I
else {
'( lemP = t6,r, -, ,'n* '
temp:.'q ;
f if end of linked list is encountercd '/
I go to last node'i if ( temP == ;t1911 ;
204 Understanding Pointers In C Chapter 4: Pointers and Structures 205

{ retum c;
pdntf ( tl]herc are less than %d elements in list', loc ) ; )
relum ;

I f debtes lhe speciied node from the linked list '/


) delete (strucl node "q, inl num )
{
f insert new node'/ stuct node .old, 'temp ;

r = malloc ( sizeof ( stucl node ) ) ;


rldata=num; temp=.q;
r-> link = temp .> link;
temp -> link = r; while (temp l= NULL )
){
if (temp -> data == num )
/* displays the contenb of he lhked list
-/ {
)
display (structnode'q I if node lo be deleted is lhe fEt node in the linked list'/
( if (temP =='q 1
printf("\n")i (
'q = temp -> link i
/' traverse the entire linked list'/ f frEe the memory occupied by the node 'i
while (q l= NULI) free (temp ) i

{ 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

) would fail, since *q (i.e. p is non-NULL). Now temp is made to


point to the first node in the list through the statement
o/od
p ntf ('\nElement notfound', num );
) temp = 'q ;

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:

(a) The node is being added to an empty list.


p telnp
(b) The node is being added at the end ofar existing list.

In the first case, the condition

ll(-q == xU111

gets satisfied. Hence, space is allocaled for the node using t


malloc( ). Data ard the link part of this trode a.e set up using the
statemeflts:

temp -> data = num '


temp -> link = NULL
E I

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

this link gets established

There is often a confusion as to how the statement temp = temp ->


link makes temp point to the next node in the list. Let us Before Addition
underctand this with the help of an example, Suppose in a linked
list containing 4 nodes temp is pointing at the first node. This is
shown ill Figure 4.7.

temp

EC I,T.*l f,-f,ool ET,;] I;F*{


150 910
After Addition

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

temp -> link:1 '


(which is same as 'q) to the ext node arld then deleted the earlier
node.

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 addafter( function pemits us to add a new node after a


)
specilied number ofnode in the linked list.

To b€gin with, through a loop we skip the desired aumber of nodes


after which a new node is to be added. supDose w€ wish to add a
new node oontaining data as 99 after the 3d node in the list. The
positiofl ofpointers once the control rcaches outsidc the for loop is nodc to ba dcleted - 99
shown in the Figue 4.10(a), Now space is allooated for lhe nodc to
be inserted and 99 is stored in the dats part of it. All that rernains Beforc Del€tton
to b€ dorc is leadjustment of link6 such that 99 go€s ir bctweeo 3
and 4. This is achieved through the statements

r.> link = t€mp -> link;


temp -> link = r i

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).

LiDk€d list of floats

Linked list ofnames


i
__-L
l*l I
(.) Bcfore Inrertion

LiDled list of Structrcs / Records

N st n.is for NULL

fb) Alter Insertion


Figure 4.11

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<

stucl node f if fist is eflpty or if new nods is lo be inserGd b€forc


( he fEl node Y
inl dab ; it('q == NUIL ll('c ) -> dala > num )
struot rbd€ link ; {
); 'q =r;
('q)>link=bmp;
main( ) )
(, ebo
- sfud node'p;
p , 11911 ; f smE{y ttnk€d tbt r/
,(
f. hat eE6 fie enliE linlsd llst h s€arch tle po€lton b lns€n
tp rcw node '/
Edd(&p,5); while ( unp l= NULL )
add(&p,1); {
add(&p,6)i il ( bmp .> data <= num &E ( lomp .> llnk .> data > num ll
add(&p,4)i bmp.> ltnk = NULL ))
add(4p,7); { .> llnk = tsmp ) .
r link
. clrsc( ) i blrptllnl=r'
dlsplay(p); lB M;
ptlntf('hNo. ot Blanr€nb h Llnkod Ust = 96d', coufl[ (
p) );
)
bmP = 51, -, ,nl( , f go b fi6 mxt node '/
d.let€(4p,7) )
dslsts(&p,4) )
dsloto(&p,5) )
dsl6b ( &p, 9 )
f dipbys fi6 conbnE ot ho llnkod lbt ./
display(p); dbday ( stnd nodo 'q )
printt ( tNo. of sl€monts in Unked Ust = 96d', munt ( P ) ) ; {
) pnnf ( 1D') ;

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

prinf ( "hNo. oI elements in lhe DLL = %d\n', d_ount ( p ) ) ;


f stucture reprBsenling a nod8 of lhe doubly linked list '/
sIuct dnode )
{
struct dnode 'prev j
f adds a new node at the end of the doubly linked list '/
d_append ( strucl dnode 's, int num )
lnt dala ;
stucl dnodB ' nsxt ;
{
slruct dnode 'r, 'q = 's ;
);
main0 f if $e linked list h empty '/
ir('s == NULL )
{
struct dnods 'p i
{
fcreate a new node '/
I list'/ 's = malloc (sizeof ( structdnode ) ) ;
P = NULL empty doubly linked
's))prEv=NI,JLL;
d_append &p,11)j 's ) .> data = num '
d_append &p,21); 's))next=NULL'
)
clrsc( ) j else
d-display(p); (
plintf ( lnNo. of elemenb in the DLL %dvt', d_count ( p ItraveGe the linked list till the last node is Bached '/
))
while ( q -> next l. NULL )
= ;

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

r = malloc ( sizeof ( slruct node ) ) ; pdntf ( '%d ', q ) data )


r-> data = num i q=q_>link;
./ )
I if list is empty or if new node is to be inserled before the lirst node )
if( 'q == NULL ll (-q ) -> data > num )
(
tq=r; f counts ttle number of nodes present in the linked list '/
count ( struct node ' q )
( 'q ) -> link = lemp ; {
) intc=0;
else
( ftraverse lhe entire tinked tht ./
f faveBe the enlire linked list to search the position to insefi while (q != NULL )
he new node '/ {
while (temp l= NULL ) q=q)link;
t c++ ;
if (temp.> data < num && (temp -> link -> dah > num ll )
temp ) link == NULL )
{ Etum c :
r.> link = temp.> link i
)
temp -> link = r '
retum i f me4es he tm linked lists, resld,rting the common elements to occur
) only once in fEfnal list '/
temP = 1660 -,1,n* fgo b nexl node'/ merye ( stnrcl nod€'p, slrucl node,q, slruct node -s )
) {
stuct node 'z ;
r-> link = NULL;
temp -> link = r' z = NULL ;
)
I f if both lisls are empty '/
ir(p == NULI &&q == NULL )
f displays the contents of the linked list '/ relum ;
display ( struct node'q )
{ ftsaveFe Mh linked lists tilllhe e nd. lf end of any one list is Eached
pintf("b') ; loop is teminated '/
-/ while ( p != NULL &8 q t= NULI
f faverse the entire linked list
{
)

while (q l= NULL ) f '/


if node being added h the lirst node
t if ( 's == NULL )
284 Undersnnding Pointers In C Chapter 5: Pointers and. Data Structures 285

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

poly_append ( &econd, 2.5, 5


multiplioation. The program that can pelform these operations is
poly_append ( &second, -3.5,4
given below.
poly_append ( &s€col|d, 4.5, 3 )
*/ poly_append ( &second, 6.5, 1 )
/' Program 61
*/
/* Program to add two polynomials maintained as linked lists
pdnf( 1n\n' ) ;
#include 'alloc, h'
display_.loly ( s€cond ) ;

/' 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

intexp; Pdnf( 1r n');


*link
struct polynode i
poly_ddition ( fBt, second, &total ) ;
); I
display_poly (tolal ) ; displaF the rEsultanl polynomial '/
void poly-append ( slruct polynode '", float int ) ; )
void poly_addltlon { struct polynode ', struct polynode',
slructpolynode")i f adds a bm to a polynomial '/
toid poly_append ( stuc{ polynode'q, float x, int y )
main( ) {
( sfud polynodo lemp ;

struct polynode *lirt, 'second, 'btal; bmP ='q '


lntl=0;
f cEates a norv node if fie list is eflipty 'i
firct = semnd = btal = NULL f lists'/ if ( 'q == NuLt 1
; empty linked
{
poly-append 'q = malloc (sizeol( stuctpolynode ) ) ;
( &first,'1.4, 5 ) ;
poly_append (&firct, 1.5, 4 ) ; bmP='O'
poly_append (&irst, 1.7, 2 ) i )
poly-append '1 ehe
( &frst, 1,8, );
poly.append ( &first, 1.9, 0 ) ; {
f traveBe he enlirE linked list'/
wltile ( Gmp -> link != NULL )
clrsc( ) ;
bmP = tqrp -t,,n* '
328 Understanding Pointers In C

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:

-j Pointcrs flnd Arrays


' Poinlers and Stnrctures
'.- Pointers and dynamic nrenlory Ilocalion
-- Pointcrs to FLrncrion\
Pointels and !,ariable argulncnls Iists
Nerr, far and huge pointers
Pracrjc l usc olpointers
Usine pointers to cxplorc Boor sector. paflition table.
Directory slructurc. etc.
Pointers aDd virns like activitics
Pointcrs and Doubly linked lists. Circular lists. Binarv
lrce{ anJ l h..:rJ<d b,niry lrcc\

P,'rnr(r.lr) ar )orrr dour m<rn) c\lra\. I rnlc rt h.r{ thil Inrtc J


( nropr"nrrer. liti ccsr<,. Ilo\e\cr. rl not us.J ptonerl).
poinrer{_hclp }ou d,' sornerhrng heroical|r .rupid deaj rhi,
b,rck anJ resjst lhat tcmptation.

$€bsite : $arn:bpbonlitre.com

You might also like