SlideShare a Scribd company logo
1 of 255
Download to read offline
i
ElrrrE
lrrytsaIE
E
ffi{r,
G6
E-
@
G'E
-
Y,,^
t f"ttti
l-.:.
.I'PB PUBLICATIONS
Table of Contents
Aclotowledgments
2. Pointers atrd Arrryr ...
Jntrcduc|ion Io Second Edhiot
IDtroductio[ To Poitrters,,,,,....,..;...............,.......-.......1
The & and , Operctors, 2
Poifier Explessions, 4
The Jargon of Pointers, 9
char, int andfloat Poihters, 9
Passing Addrcsses to Functiohs, 12
Fuictions Retuming Pointers, 15
Solyed Problems, 17
Exercise, 30
Pointers and Stings, 142
The const Qualifier, 143
Retumirrg eonst Yaluef, 146
Two Dirtensional A|ray ofCharacters, 147
Array ofPoirers to Strings, 149
Lirnitario4 ofArray ofPointers to Strings, I 52
Solved Problems, 154
F,xerclse. 184. t
tv,'4. PolnterrandStructures ......,..........------------.,.........189
An Array of gructures, 191
Mole about Structures, 192
Structure Poi ters, I94
Offsers ofstructufe Elemehts, 196
Linked Lists, 200
Stacl$ and Queuet, 220
Doubly Lhked Lisk, 2ii
Solved Prcblens, 243
Etercise,270
5. Pohters rlrd Dats Structurcs ...,......,.,..........,,,,.....,,,...,....279
Mergirrg dLinked Lists, 280
t-
llhat are Arrays, 38
Passing Atay Elernents to a Function.
Poihters and Atays, 43
Pqssing a4 E ttirc Affoy to a Function,
TheRealThing,5l
Morc Thqn One Di ension, 52
Poinlers arrd Tfuo Dimetsional Arrays,
Poi tetto sn Atay, 58
Pdssing 2-D Arroy to a Function, 59
Three Dimensiondl Arrays, 62
Passing 3-D Array to a Functiok, 66
Retuming Aftayfrorn Fuictiot , 69
Relumifig 3-D Aftay from a Function,
Array of Poi ters, 82
Dyuhtic Memory Allocation, 84
Solved Problems, 87
Erercise, 130
Pointers and Stiitrgs ,.....................133
Wat are Slrings, 1j3
* Li ked Lists and Polynonials, 285
Sotting a Lin*ed List, 297
Circalar Linhed List, 323
Trees, 326
Binary Tre*, j28
41
50
3.
Stqhdard Library String Funcrions, I38
vt
Traversal d a Binary Tree, 33 1
Deletionlrom a Binary Tree, 336
Threaded Binary Tree, 344
Graphs,356
Solved Problems, i69
Exercise. 389
6. PointersMisceIlrtry..,,,.....................................................391
File Poi rets, 391
Pointers to Functions, 394
typedef with Furrction Potuters, 397
srgc and srgv - Arguments to mairt( ), 398
Poin ers afid Ydriable Nurnber of Argunen s' 399
rcor,lat and huge Poinlers, 40i
Which Poi en to Use?, 408
Physicol ,4ddrcss to Segne :qsel 4 I I
The Darcing Dolls, 412
Caps Locked!, 413
How Much Memory Do You Have?, 415
Exercise,4l7
7. Appllcrdorr of Pohters '..,....--........................................423
Exploting the Dith 423
Dictioiary, 434
Manoging Database, 439
The Keybod Queue, 459
InJix to Postfa, 462
Evaluation of Postfa Exprcssion, 467
Locatw Duplicote Filelanes, 469
Eoshing 474 i
Function Calls and Stqck. 480
Solved Probtens, V85
I
tnrex | 493
Preface to Third Edition
In all walks of life anythiDg can be done better the next lime
around. I realised this more emphatically when I completed lhe
third edition oftlds book. Ihus, Ore so-cJlled ,perfect'
c'hapters of
the second edition had to be redone for more clarity and simplicity.
For quite some time now I have beeo getting requests fiom
readers that the chapter on .pointers
and Oata Structures, be
made more elaborate and exhaustivg. I have completely
overhaule.d this chapter. Now it also includes binary treis ani
graphs,
While reading the fust draft ofthis edition I felt that something
is missin-gin this book. It was only when I was ttuougtr *ittr rtr!
final draft I.realisgd that the missing link (poinrer) wa-s a chapter
on applications of pointers in real-world programming. After
all, no amount of theory is useful unless you cun poi it into
practice. So the final draft became semifinai since I decided to
add this chapter to the book. And now I am presenting you the
edition which I feel is complete in all respects, lili I
"-pmying tlat I won't be required to wrire aflother editiol of this
book, Any author would testiS/ that writing a new edition is
always more palD in the neck than writing a fresh title.
tt
Poihten ca be tuade to work ifyou frddle ,a,ith them lo g
e ough. Ifyou Jiddle with anything long enough you wilt uttimately
fiess it
An Introtuctionto
Qointrs
f f Tbich featue of C do beginners find most difficulr to
VV understand? The answer is easy: pointers. Other
v V languages have pointeE but few use tbem so freely, with
such abandon, as C does. Aod why rct? Ir is C,s clever use of
pointeN that mak€s it the excellent language it is.
The difficulty begiDners have with pointers has much to do with
C's pointe, terminology than lhe actual concept. For instance.
when a C progmmmer says that a cedain variable is a
.
pointer..,
what does that mean? It is hard to s€€ how a variable can poinr to
something, or in a certain direction.
2 Understanding Pointers In C Chapter 1: An Introduction to Pointers 3
It is difficult to get a grip on poioters just by listening to
programmer's jargon, In our discussion of C pointers, therefore,
we will try to avoid this difliculty by explaining them in terms of
simple programming concepts. The fi$t thing vi,e want to do is
eplain the rationale ofC's pointer notalion.
We oan print this address through 1Le
/- Program 1
*/
main0
{
inti=3;
following program:
The& and * Operators
Consider the declamtion,
This declaration tells the C oompiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Srore the value I ar this location.
We may rcpresent i's looation irl the memory by the following
memory map:
i-__}
El--*6485+
Location Dnme
I-ocation no. (Ad&ess)
Figure l.l
We see that the computer has selected memory Iocation 6485 as
the place to store the value 3. This location number 6485 is not a
number to be relied upon, because some other time drc computer
ult
r,
may ohoose a different location for storing th€ value 3.
impofiant point is, l's address in memory is a number.
printf ( "nAddress of i= %u^,
prlntf('hvalue of i = %u", i)
)
l'he output ofthe above program would be:
Addrcss ot i= 6485
Value of i= 3
&i) ;
inti=3;
l,ook at the fi$t printf( ) statement carefully. The .&, opeBtor
[sod in this statement is C's 'address of operator. The expression
&i retums the address ofthe vagi4llglwhich in this case happens
lo be 6485
pointer operator avaikble in C is '*'. called 'value at
erator. It retums the vaiiE stored at a particdlalEddfess.
also called an 'indirection'at address' operator is
l,hlene carefully the output olthe following programj
/' Program 2 '/
nrain0
I
inti=3;
printf ( "nAddress of i = %u', &i) ;
%d-, i) ;
%d",.(&i));
printf ( nvalue ofr =
other
ess o
e'value
orator.
printi ("nvalue of i=
)
Ttre
IJnderstanding Poinlers In C Chapter I : An Introduction to pointers4 5
The output ofthe above prog€m would be:
Addressoli=6485
Valueofi=3
Value oli = 3
Note that pdnting the value of *( &i ) is
ofi.
As you can see, i,s value is 3 andj,s value is i,s address.
"l:1^1"]! ". :an'r use j jn a program wilhout dectaring it. And8rn.e j rs a arjable. which conlains lhe addre., of i, it is-aeilurea-0r.
lnl 'j ;
'lltis declaralion tells the compiler that I will be used lo store therddress ofan integer value _ in o*re. *Jro.; poino ,o _ iri"g;;Ilow do wejustify tlie usage of * in the declaiation,
lnt'j;
1;d
,t g:-Py the meaning of +. It stands for ,value
at address,,
I hus,.irt *J would mean, the value at the addre*
""","rn"ji, ij,
same as printing the value
Pointer Expressions
Let us now see what are pointers and how they can be used in
various expresJions. We hav9 seen in the previous section that the
expression &i retums the address ofi. If we so desire, thig address
can be collected in a variable by saying,
But rcmembcr that J is not an ordinary variable like any other
int€ger variable. lt is a variable, which contains the address of
llcre is a program that dcmonshates the relationships we havet ccn discussing.
another variable (t in this case)
Since J is a variable the compiler must provide it space in mernory'
Once again, the following mcmory map would illusts?te the
contents of I and J.
E'.-l
6485 3276
Figure 1.2
j=&i;
I Program 3./
maino
(
inl i= 3;
int 'j ;
j=&i;
pdntt ( 'nAddE$ of i = %u', di ) :
printf ('nAddEss of i = %u'. i ) :
Printf ( 'nAddress ofj =
o/ou',
ai) ;
pdntt("nvalueotj=%d'. i ) :'pdntf ( 'hvatue of i = %d", i i :
pdntf ( 'hvalue of j
=
o/od,. .{
&i ) I .
Printf ('nvalueof i = %d' l) "'
6 (Jnderstanding Pointers In C Chapter 1 : An Introdaction to pointers 7
The output ofthc above program would be:
AddEssoli=6485
Addressofi=6485
AddEssofl=3276
Value ofl = 6485
Valu6 ofl = 3
Valueoli=3
Valu6 of i= 3
Wo* thrcugh thc above program caretulln taking hclp of the
memory locations of t and J shom ea isr. This program
summarires everything we have discusscd so far. If you don't
understand thc'program's output, or the meoning of ihe
oxpregsions &1, &J, rl ard *( &l ), re'read the last few pages.
Evcidring wc say about poilters ftom hcr€ onwards will dcpcNd
on your understanding ofthcse exprcssions thoroughly.
Look at the following dcctarations,
lnt'alpha;
ohar 'ch ;
lloat 's :
Hcrc, rlphr, ch and I ale declarcd as pointer variablel, i.c'
variableicapable of holding addtesses. RfiIember that, addrgsses
(location nos,) ar€ always going to be whole oumbe!$, thorcfore
pointers ahvays contain whole numbers. Now we call put these two
iacts togethir and say-poiotels are variables that contain
since addrcsses ai;;lwaysE;G;mBEiies!way
would always co!!Bi!
concept of pointer caD be further extended. pointer we know is a
vadable, which contairc address of another variaUte, Niw thii
variable itself could be another pointer. Thus, we now have a
pointer., whicb.contains another pointer.s address. The following
example should make this point clear.
f Prcgram 4'l
maino
{
iiqt i= 3;
int'j:
lnt
nt;
j= &;
k=&j;
pinf ('bAddr€ssof I = %u., & ) ;
Ptinu ( trAddcss oti= oi6u', j ):
pdntf ( lnAddEss of i = %u.,
ik
) :
Pdntf ( 'nAddrsss ofj = %u', &j i ;
pdnf ( lnAddrEss ofj= %u', k ):
prinf ( tAddrBss ofl( = %u', &k ) ;
prinf ( lnhvdus ofj = %u', j);
pdnf ( Walus of k r %u', k );
printf ( 'nvalue oti = %d', t)j
pdntf( lnvaluo ofi =/od',.(&j))j
pdnf (hvalue of i = %d", J );
pdnf( lnvalueofi = %d',,* );
The declaration llgat *Ejqes not mean lhat s is going [o cooBln a
fl oati-ng-point valqq. @
--aterisi-oIa'hoating-point
value. Similarly, char *ch means that
ch is going to oontiin the address of a char value. Or irr other
words, the value at ad&ess stored in ch is going to be a ch'r' The
The output ofthe above program would be:
Addressoti=6485
Addre6sori=6485
AddEssofi=6485
AddEssofj=3276'
8 Understanding Pointers In C
Address ofj= 3276
Addressolk=7234
Value ofj= 6485
Valueofk=3276
Valueoli=3
Valueofi=3
Value of i= 3
Valu6ofi=3
The following memory tDop would help you ir tmcing out how the
prcgram prints dle above outpul.
Figurc 1.3
Obs€rvc how the variables l, J and k have been declarcd,
inti;
lnl
-l
i
int -k i
this, one mrely requires to
just in case...
extend the definition of a Pointer' But
H€re, I is an ordinary ldt, I is a pointer to ar lnt, whsreas k is a
poiflrer to a pointer. ln pdnciple, there could bG a pointer to a
;ointer to a pointer, or a pointer to a pointer to a pointer to a
pointer. There is no limit on how far can we go on extending this
a€finition. Possibly, titl the point we can csrFehetrd it' And that
point of oomprehensiotr is usually a pointe, to a pointer. Beyotd
char, int zad.Jlod, Pointers
Considei the followiog program:
f P@gran 5'/
main( )
{
charc,'cc;
int i, 'ii;
I
3
J
6485
k
3216
6485 3276 1234
The Jargon of Pointers
Consider the following program segment:
inta=35;
inl 'b :
b=&a;
Now can you guess which ofthe follo.f,ing statemenis are coneotl
(a) b contains address ofan ht.
(b) Value at address contained in b is an lnt.
(c) b is an ltrl pointer.
(d) b points to an t!t.
(e) b ig a pointer which points in the dileotion ofan lnt,
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
b contained an address of a flort it would have beoome a flolr
pointer. with the same argument if we have three Doiflter variableg
first containing addrcss oian array, second contai;ing ad&ess ol,a
structure and third containing address of a fuflction then It woulo
be appropliate to call these ai an array pointer, a structure poinler
and a fiinction pointe! respectively.
float a,'aa;
c = 'A I ascii value of A gets stored in c
t/
i=54;
a= 3.14;
ii= &i i
aar&ai
pdntf
plintf
pdntt
p ntf
pdntf
printf
)
And herc is the output, , ,
Address conhined in cc = 1004
Addr€ss contain€d ln il = 2008
Address c.ntalned in aa = 7006
Vslue ofc = A
Valui of i: 54
Valueofa=3.140000
Note that in the prltrtf( )s the addresses of chrr, lnt ard lhe no't
all have been prioted using the fomat specifier 7ou, Sometimes
the address miy tum out to be a number smaller than 32767. ln
such a case we may use the fomat specifier 7"d to pritrt the
address. Also observe that though the integer va able i occupies
two brtes in mernory the stalement ii = &l stores only the addEss
ofthe first blte, 2008 itr il (refer Figurc 1.4). Similarly,
" = &a
stores only the address of the flrst byte (7006) out'of forE bytes
occupied by the float variable a.
Chapter 1: An Introductia to Pointers t1
Figue 1.4
Thc address of first byte is ofton known as thc base addrcss.
Though ll and rt contain ody the base addrcsses, the e*ftdssions
*ll and *aa allow access !o all the bytes occupied by the intcger I
and a rcspectively. This is because il and a& haye been dcclarcd as
itrt and llort pointers respectively. Since il is an itrt pointer, *ll
must fetch ar lrt. Similally, since aa is a flort pointer *ar must
fetch a lloat.
Do you &ink the following program would work? And if it does
what would be its puttr ui?
Address contained in cc = %u", cc ) i
'nAddr€ss conbined in ii = %u", ii ) ;
'nAddl8ss ontained in aa = %u', aa ) i
"ivalue of c = %c', 'cc ) ;
lnvalue of i = %d', 'ii ) ;
'Vrvaluo of a =
o/ol,
"aa ) ;
f ftogram 6'/
main( )
{
inli=54;
float a = 3.,l4;
char'ii, 'aa ;
ii= ( char
.
)&i;
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',
) :
EI1004
lE;;l:;7l
2009
ii
m8l
7602
7006 7007 7008 7009
@1962
3.14
,13
12 Understanding Pointers In C Chapter l: An Introduction to Pointers 13
p ntf ( "hvalue at lhe addrcss contained in aa = %d', 'aa ) ;
)
Note that here ll and aa have been declared as chsr poioters. Still
rhe statemenrs ll = &i and ra = &a worElqnce again tbe ad&esses
2008 and 700d (refer Figure 1.4) get stored in ll and m which are
printed through the first two prtntf( )'s. However, the prcgram
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
one contained in 7006, 7007, 7008 and 7009.
Moral is, ifyou vdsh to acoess an integer value stored in a variable
using its addr€6s, it's rccessary that the ad&€ss be stoEd in an
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
a float pointer.
Passing .dddresses to Functions
Aryu.ments arc generally passcd to fulctions in one of the two
waysr
G) Bending the values of the arguments
sending the addresses ofthe arguments(b)
In the first method the 'value' of each 4crzal atgumetf in the
calling functiol is oopied into aonespondirg forr al argumcnt of
the called function. With this method, ohanges rnade to tlre fotmal
argume[ts irr the called function have no effect oo the values ofthe
sqtual argum€nts in the calling function.
following Eogram illustrates the 'Call by value'
r p.J,l,ff z r
(
inta=10i
irt b = 20;
swapv(a,b);
pdntf(tla=%d",a);
printf('bb=%d',b);
)
swapv ( int x, inl y )
{
pdntf(u=%d",x)i
Printf (y = %d", y )'
)
The output ofthe above program will be:
x=20
v= 10
a=10
b=20
inlt;
t=x;
x=y;
y=t;
Note that values of s and b remain unchanged even after
exchanging the values of x and y.
In the secold method (call by reference) the addresses of actual
arguments in the calling futlction are copied into fonnal arguments
ofthe called function. This means that using the fomal argumeflts
in the called funotion, we can make changes in thJ actual
arguments of the calling function. The following program
illushates this fact.
14 Understanding Pointers In C Chapter 1: An Introduclion to Pointers 15
areaperi (radius, &area, &perimeter ) i
printf ( 'Area = %f, area ) ;
printf ( 'nPerimeter = %f', pedmeier)j
areapei ( int r, ioat 'a, float
*p
)
'a = 3.14'r'r;
'p = 2'*3.14' r;
And here is the output...
Enter radius of a circle 5
Area = 78.500000
Perimeter = 31.400000
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 chaflge effective even in main( ). That is why when the conhol
retums fiom the function areaperi( ) we are able to ourpul the
valuos ofiare! and perimeter.
Thus, we have been able to rctum
firnction. This helps us to overcome
f Progtam 8
./
main( )
{
inta=
intb=
swapr (&a, &b ) ;
pdntf ( "na =
o/od"
printf('nb=%d"
i
swapr ( int
*x,
int
-y
)
{
inlt;
t=-li
)
10;
20l
,a);
,b);
The output ofthe above program would be:
a=20
b=10
retum more than one value at a time, _which is not possible
ordinarily. This is shown in the program given below. lime
statement, which can rctum only one value ftom a function at a
Using 'call by reference' intelligently we can make a function
/. Program 9'/
main( )
{
int radius i
float area, perimeter j
printf("nEnter radius ofa circle " )j
scanf ("%d", &radius ) ;
Functions Returning Pointers
The way functions retum an int. a float. a double or any other.lala
tlpe, it can even retum a pointer. Howevei, to make a funcrion
retum a pointer it has to be explicitly mentioned in the calling
function as well as in th€ function definition. The following
program illustrates this.
two valuos from a called
the limitation of the return
16 Understanding Pointers In C Chapler L An Introdu( tiott to Pointers 17
/* Program
main0
{
u",p);
d",-p);
int'p;
int
-fun0
;
P=fun0;
printf ( 'n%
printf ( "n%
10-t
/" prototype declaration */
*iun(
) /- function defnilion */
inti=20;
relurn(&i);
Solved Problems
lAl What will be the output oflhc following programs:
(1) main0
t
int i= -5, j= -2;
junk (i, &j);
printf ( 'ni = %d j= %d", i,l
junk ( int i, int
tj
)
(
l- I li
)
);
int
t
)
This progmm shows how a pointer can be rctumed from a
funotion. Note that the prototlpe declaration tetls the compiler that
fun( ) is a function which receives nothing but returns an integer
pointer. The first prlntf( ) would output the address contained in p
(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
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
shown below:
static int i = 20 ;
-5j
variable names in differcnt functions? Yes, by all means,
without absolutely any conflict. Thus, the two sets of i and J
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( ),
Jutrk( ) gets reflected back in maitr( ). Hence
evaluates to 4 is reflected back in main( ).
any
-J-
change in
*j, which
Output
Explanation
One doubt immediately oom€q to the mind----can we use same
18 Understanding Pointers In C
(2) #include "stdio.h'
main( )
{
int a, b =5;
a=b+NULL;
printf('%d',a);
)
Output
5
Explanatioa
NULL has beea defined in ',stdio.h,' as follows:
#define NULL 0
Heroe, duiing peprocessiog NUff *,in be rrplaced
resulting into 5 getting stored irr r.
(3) #include 'stdio.h'
maioo
(
- printf ( '%d %d', sizeof ( NULI- ), !*zeof(.. ) ) ;
)
Output
21
Explanotiot
Chapler 1: An Introiluction to Pahtters
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.
Even though the string -' is empty it still contains the
character, '0'. Hence its size arrrrs out to be I bvte,
(4) main0
{
floata=7.999999;
float'b,'c;
b=&al
c=b;
printf ( tu%u %u %u', &a, b, c ) ;
. printf (tl%d %d 96d 96d., a.( Aa ),.b,'c );
I
Output
4200 42N4N0
0 24576.318115
Explaaatioa
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
prtntf( ) prirfs the address of a in three differcnt ways. No
problem therc. What is supdsing is the output of the second
printf( ). Through this pritrtf( ) we are attempting to print
7.999999 by. applying pohler operalors on a, b and c. a,
*(&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.
19
bv o,
20 Understanding Pointers In C
So always remember to use 9/"f to print floating point values.
Don't rely on printf( ) to truncate a float value to an integer
du ng pinting by using a yod. Vice versa also it is t[ue. The
following statements wouid not print 7.000000. Don't be
suryrised ifyou get some odd value. In that sense y"d and ohf
are a Iittle unreliable.
inti=7;
printf("%f',i):
(s) mainO
(
, int.c;
c=check(10,20);
printf("hc=%u',c);
)
check ( int i, intj)
(
int.p, rq
;
p=&i;
q=&j;
if(i>=45)
retum (p );
else
retum (q ) ;
)
Output
Enor message: Non ponaue pointer assignment in main
E)tpltiafion
The rcason for the eror is simple. The integers being passed
to check( ) arc collected in i and j, and then their addresses
Chapter l: An Introduction to pointers 2l
are assigred to p aDd q. The[ in the next statement the
conditional operato$ test the value of i against 4j, anJ ;;tu;either the adtlress stored in p or the adjress ,t""J iil. f"t
appeaE that this address would be collected in c in maijt t
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 intefer. Thus j"ust
declaring c as an iDteger pointer is qot sufficient. We must
make the following modificaaioru in the progmm to make it
work properly.
main0
(
int 'c j
inl 'check ( in! int ) ;
c = check (10, m );
pdntf(tuc=%u.,c);
)
int 'che6k ( int i, int j )
)
(6) main( )
t
tloat.jamboee ( fod.);
float P = 23.5, 'O ,
q=&p;
pdntf ( tlq bebre cdt = 96u', q ) ;
q=jamborBe(&p);
printf ( q afler ca[ = %u., q ) ;
tloal 'jamboree ( foat t )
t=t+1:
Unders tatding Point ers W Chapter l: An Innoduction to pointers 23
rBtum ( r) ;
)
OutPut
q bebtB call = silg8
q aier call = 5502
Explatation '
[Bl ANwer tb€ folowing:
Explatatioa
(
tpb
)++
ln mrtd ). q has be€a d€clarEd as a trott pointer' lt means q
;; ;-G;il capable of holding the addtess of a flori
rrt-rnf, o = Cr'm
"aat"""
of p' a ltoal is stored ia q and
,fr*,i"fu "ri,t-"gl
th" p"iotf( ) This is the value of q
il.i.,{'i"i-urt-*t li"Erle<I.'whetr-irmboree( ) i8 called the
ffi;:Jir;i" "X; i, -a i" *u""t.a i"
''
At this^juncture
r contains 5498 lwhen $'e ratr the progmm it was 54vui wnen
,a"
"*a"a"
*" paga- this may tum our to be somc olher
lia*""1. Wr,* t i.ircremented it would become 5502 whv
.-"t* #+i S*""* . is a tro.t pointer aDd on incrmentiflg il
i"'iii*.rfa poin r. {re nert ll'oat which would be F€sent 4
iL*. rt"oo. il*. cvery Oo.t is 4 bytes lotrg The return
"tat"rnent
tl"o rett^" lhis adrlress 5502 back to EalD( 
Since a llo.t poiott is bsitrg retume4 a deElaration-.lloat
*lembore. ( flort') is necessary in main( ), whrch tolls me
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
a llort poirtcl.
(2) !r th€ followinS gogrm add a stat€.ri€ot in the fi[roiion
fu( ) such tllat ad&ess oft gels stored h l.
L
main0
{
int'jl
roidtun(i -);
tun(&j);
)
void tun ( int -k )
t
inl a ='10;
I add staEment he,E
*,/
)
Explatation
'k=&a;
the pofut€r and oot the value pointed
iacrements tle value befug pointed to
( I ) Can you write anoth€r exEessioo which does the same Job as
.-1'pE9
9) Are the expEssiotrs ipff+ aod #rph saDe?
Explanation
No. *Ptr+ inorcments
by it, whereas, +rph
by ptr.
(4) Where can poit*€rs ie used?
Explarration
{Jnderstanding Pointers In C Chapler l: An lntroductian to Pointers 25
At lot ofplaoes, some ofwhich are:
- Accesshg array or s&ing elements
- Dynamic memorY allocation
- Call by refereace
- Implemeding lioked lists, tre€s, $aPhs and many other
data structures
Eiplanation
No. An efior would be .eported i[ the statement k+arithmetic on void pointeE is Dot permitted unless the
slnce
void
(5) Would the following
waming? <Yes/No>
main0
(
ioat i = 10,1;
bid'k;
k=&i;
j= k;
pdntl(ln%f,l);
)
Erylaaation
Eogram grYe a comPilatioo enor or
pointer is appropdately typ€casted.
(7) Would the following prograrn
compilatioo?
#include 'stdio-h'
main0
(
int'p1, i= 25;
void .p2
;
p1 =&;
p2=&i;
p1 = p2:
p2=p1;
)
Expla ariqn
No
(8) Would the following program
compilatioa?
.
#include 'stdio.h'
main0
{
float
-p'1,
i= 25.50;
chat
*p2,,
pl=&i;
p2=&i;
)
Explaaatiott
give any wamiug on
give atry waming on
No. Here no tipecastirg is required while assiguing thc value
t
-*Jto. I L""ugrao*lsioq" ,"t" uopl&d-gU@or'"ntlv
*teo ooo po-i"tertypes are assigned to atrd fiom vold ''
(6) Would thc followiag Pmgr& contpile?
main( )
{
int a = 10,1;
sid'k;
i=k=&a;
j++ ;
k+;
printf ( lyou %u', i, k ) :
Unders landinE Pointers In Chapter 1: An Introduction to Pointers 27
(
Yes. The wamfug wonld be "Suspicious pointer conversion itr
firnction maitr( )".
9) What is a oull point€d
Explanation
For each pointer typ€ 0ike say a char pointer) C defines a
speoial pointer value that is guara eed trot to point to any
object oi fiuctiotr of that type. Usually, the null pointer
consta used for rcprcse itrg a dull pointer is the integer 0.
Ud WUf" fi" Aff"r.o"" between a null pointer. a NULL macro.
- the ASCII NUL character and trullstring?
Explanatiot
A null pointer is a pointer, which doesd't point a[ywherc'
A NULL nla ro is us€d to represeot the trull pointet in source
code. It has . value 0 associat€d wilh it. l
The ASCtr NUL character has all its bits as 0 but doesn't
have any relationship with lhe null pofuter.
The trull string isjusr atrolher oame for aD empty string "".
(l l) In which header file is the NULL rnacro defined.
Explanotioa
, In files "stdio.h" and "stddef.h".
(12)Is the NULL poirti:r same as
<Ye$No>
Explakation
No
an uoitritialised pointer?
Ellvironltre set two
of,tlE data segnent and
(13) above for details).
(l3)What does the error ..I{ull pointer Assignment, mean and
what causes this e.rofl
Explanation
The Null pointer Assignment eEor is generated only ia small
ard medium memory models. This error occurs in programs,
which attempt to cbange the bottom ofthe data ,"gJ;t..-----'
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;iBodand Intl.". In the small and medium -".ot;;"i;;;null pohter points to DS:0000. Thus assignhg u ;ulu; ;;;memory refer_enced by this pofuter wilt ov;rwri-t" tte nrsi ."ioD,,le In fie data segnent. At progmtD terEination, the four
zercs and rhe copydght bamer arE ch€cked. Ifeithei has been
mo.di fie4 then rhe Null poiDter Assigftretrt error is generated.
Note that the oointer may not truly be Du[, bur maibe a wild
polnter that rcferences these key arcas in the data sigrnent.
( I4 ) How do we d€bug a Null poifter Assignment erlor?
Explanation
In the lrtegrated Development
watohes- -olre pohting to the bottoE
another pointing to the banne. (refer
1e
Undennnding Pointen In C
These wat hes, ed what they should display in the watch
window, are:
'(char J4,42MS 'Borland C+r - Copydght 19gl Bodand lntl.,
(ch ')0 NU|I
Of course, the copyright bamer shown above will vary
depending otr your ve$iotr ofthe Borland CyC+ compiler.
You can t)?e the following program and step through your
progam using F8 or F7 and modtor ihese values in thi witch
window. At the point wheir one of thern chaages, you have
just executed a statemerf that uses a pointer thai has-not been
prope y initialized.
#inclds 'dos.hi
#include 'stdio.h'
#nclude 'stirE.h'
main( )
(
char 'ptr, 'banner ;
pr: ( char') MK_FP (_DS, 0 ) :
banner = ( char' ) MK_FP ( _DS, 4 ) ;
sfEpy ( pt, rhi'
) ;
s[cpy ( banner, 'hello') ;
pdttf ( lncood iloming' ) ;
)
Nole that a Null poiDter Assigtrmetrt ermr is trot generaled in
all models. Il the compact, hrge atrd huge memory models,
frr pointgrs are us€d for data (Refq C-nupte" O fo, -o."mfonytion about m€mory models and far pointers).
Therefore, a null poiater will reference 0000:0000, oi tle tase
ofsystem memory, atrd using it will trot cause a comrption of
Chapter l: An Introduction to pointers 29
the key values at the base of tbe data segment. Modifuing the
base ol systern memory usually causes a system crash,
however. Allhough it would be possible that a vrild pointer
would overwrite the key values, it would Dot indicale a null
pojnter. It the tiny memory model, DS = CS = SS. fterefore,
using a null pohter will overwrite tb€ beginning of the code
segment.
( I 5) Can anlthing else generate a Null pofuter Assignoent error?
Expla atiot
Yes. using a wild pointer that hsppeDs to reference lhe base
area of the data segment may cause the same error since this
would change lhe zeros or the copyright bauner Since data
corruption oa staok comrption could cause an otherwise-valid
poi[ter to be corupted and point to the base of the data
segment, emy memory corruptioD could resull in this 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
lnitr:lize4 elac€ a- watgh on lat poirter- Srep througn your
Fogram again and watch for its value laddressj to chaige,
ICI What do the following declarations stand for?
int
*i ;
,loat -i ;
char*k;
voidf(int',chart);
floattg(floatt,ioal-);
int*h(foat',char-);
b.plahatiot
30 Understanding Poinars In C
I is a pointer to a pointer to a pointer to an itrt.
j is a pointer to a pointer to a lloat.
k is a pointer to a pointer to a pointer to a pohter to a char.
f is a function which receives an itrt pointer alld a char
pointer and rctuIus trothing.
g is a function whicb receives a float pointer and a poinler to
a float pointer and in fum rehrms a float pointer.
h is a function which receives a flort pointer and a pointer to
a char pointer and in tum rcfums a pointer to an itrt pointer.
Chapter I: An I trod ction to Pointers 31
Exercise
(2) mdno
{
shar c, 'cc ;'
inti;
long I ;
ioal t;
i='15;
I = 77'177 i
f= 3.14 ;
cc = &c;
pdntf ( trc = %c cc = %u', 'cc, cc ) ;
cc=&;
pdntl('bi= gtd cc = %d, *cc,
cc ) ;
cc = &l;
printf (1nl= %ld cc = %u', 'cc, cc ) ;
cc=&l;
pdntf ( 1nt = %f cc = %u', 'cc, cc ) ;
)
(3) maino
{
intcr10,d=m;
pdntf
pdntf
pdntf
swap
printf
pdntf
IA
(1)
I Wtat $r'il1 be lhe output ofthe following programs:
maino
{
int a, 'b,
*c, *d, *e ;
a=10;
b=&a;
c=&b;
d=&c;
e=&d;
pnntf ( 1na = %d b = %u c = %u d = %u e =
you', a, b, c, d, e ) ;
pintf ( 1n%d 96d i{d', a, a + rb, *c + Ed + tre ) ;
)
We ale in main( )....') ;
lnAddtess orc= %u Address ofd = %u", &c, 8d ) ;
lnBebre srflBp( ). c=Yod d=%d',c,d);
c,d);
!Bek b main0....'):
Afldr swaD( ), c=%d d=Yod',c,d);
)
swap (intc, inld )
{
pdntf ( lnwe ale in ${ad )....' ) ;
printl ( lnAddless ofc = %u Adrcss old = %u', &c,8d )j
pdntl (1nBetore chang€{ ), c = 96d d=yod',c,d);
32 (lnderstan"ding Pointers In C
change(c,d);
printl ( "hBack to $rap( )....' ) ;
pdntf ( "nAfier change( ), c=%d d=%d',c,d);
I
change (int q intd )
{
intt;
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 ) ;
t=ci
c=d;
d=t;
b ntf (After interchanging, c=yod d=o/d',c,d);
)
.
i4) main()
(
intc='10,d=20j
printf ( "nBeforc s!,/ap, c = %d d = 7od', c, d ) ;
swap ( &c, &d );
printf ( Affer suEp, c=96d d=96d',c,d);
)
swap ( int 'cc, int
*dd
)
{
exchange ( &cc, dd );
)
exchange ( int
*cq int
*dd
)
{
intt;
,_cc
=
.dd
;
Chapter 1: An Introduction to Pointers 33
'dd = t;
)
(5) maino
t
inta=5,'aa;
aa=&a;
a=power(&aa);
printf{'ba = Yod aa=%t,a,aa);
)
power ( int
*ptr
)
{
intbi
b =
*pt'*fitr ;
retum ( b );
)
(6) maino
{
inti=3;
foat I = 3.50, 'plod ;
float' multiply ( irt float ) ;
pmd=multiply(i,f ); A
printf ( lnplod = %u value at addess = 7ol, pn2d, 'prod ) ; t
)
ioat ' multiply ( int ii, flo6t ff)
t
float producl ;
product=ii'fi;
pdntf ( lnprcduct = %l address of prcduct =
o/ou", product,
&product) ;
rctum (&product);
main( )
{
char'c = 4000 ;
inl 'i = 4000 :
long
.l
= 4000 ;
float 'f =,1000 ;
double 'd = 4000 ;
printf ( E=%u, c+ 1 = %u', c,c +'l )
pnntf ( 1ni = %u, i + 1 =%u', i i+'l ) ;
pnntf ( trl= %u, l+ 1 = 9tu', l, l+ 1 );
printf ( f = %u, q-+'l =%u', t f + I ) :
printf ( d = %u, d + 1 = %u', d, d + 1 )
)
maino
{
int i= 10, j = 20, difl;
. diff= &j- Ai:
pdntf("haddEssofi=%u atffIess oli = %rf, &i, Ej);
pdntf ( 'hdtfeGnce ol addrEsses of i and j is %d'r'diff )i
)
main0
{
int'i,'jj
j=i'2;
Pdntf(1nj=o/6u',i) '
)
(10) main0
(
int i= 10:
pdnf (1llvalueoli=%d add€ss ofi = %u', i, &i) ;
Chapt* l: An Introduction to Pointers 35
&i= 7200 ;
printf ( lnneu ydue ofi = 96d neflddless of i= %u", i, &i):
)
(11) floata = 3.14;
float
*z
;
foal *y j
float
*x;
foal *v:
float
*u, ;
float
* tun1 ( ioat ') ;
tloat* tun2 (float-);
main( )
(
clrsc( );
z=tun1(&a)l
pnnfr ('VNiA? ,a*zl i
)
;oat*fun1(foatt)
(
Y=82;
v=fun2(&y);
retum (*Y ) ;
)
float
-* tun2 ( float "x )
{
w=&x;
retum (w);
)
lDl Strte True or False:
)
4)
(l) Multiplication of a pointer and an uDsigred integer is
allowed-
{ 2 ) Address of a float cao be assigned to a chlr poiioter.
(3) A float pointer alwa]rs cotrtaitrs a whole rumber.
(4) A pointer p contaitrs addre$s ofa pointer to a'pointer to an
iirteger pohte.. To reach the integer value we should use
No matter how much time rox hove q)ent with pointers you y,/auld
always l d so,rre application oft that woutd leave yoi guessing.
Sointm antflrays
f he C language providas a capability callecl array that enables
I the user to design a s€t of similar data types. Array is a very
^ popular data type with C progrmrnoers. Tbis is because of
lhe 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.
Understanding Pointers In C
What are Arrays
An Array is a colleotioa of similar elements stor€d in adjacent
mernory locatiom. An odirary variable is o@able of storing only
one value at a time. Howwer, lterc arc situations in which we
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
by 100 studerlts in m€mory. In such a case we have two options to
storc these marks in me.morl4
(a) Constsuct 100 vadabl€s to storE perceDtage marks obtaircd by
100 ditrcrent studetrts; i.e. each variable cootaining one
shrdent's marks.
(b) CoNtruct one v{iable (called a subscript€d va able) capable
of storing or holding all tlre hun&€d mad(s.
Obviously, the s€coDd alkmative is bett€r. A simple reason for
this is, it would.b€ rnrch easier to hodle orc %dable tharl
haodliag 100 difiem,rt ya.iables. Motsov€r, there arc cartai['logios
that camot be dealt wilh, witrcut fr€ usc ofa subsctipted variable.
Now a fomBl defiritioa of subccripfed variableg: A subscripted
variabte is a collcstivc ame give,n to a 8!oup of 'similal
quantities'. Thrs€ similt quantities oould be percentage marks of
100 studcnts, q salcies of 300 €tqloyccq or ages qf 50
snploycrs. Whst iB iryormt is |iat the quaatitiq must be
'gimilar'. Each menrber ia lhe group is reftrred to by ite position in
the goup. For ereplc, assu@ the following group of nultlbels
thrt repr€s€Et p€rs,coiagc oarts obtaircd by five stuilents.
pEr = { 48, 88, 34, 23, 90 }
If we w.nt to rEfer to ltG s€codd ntElbcr of the group, the usual
nolation used is per2. SiEilady, the foudh rumb€t ofthe group is
refsrrEd as perr. Howwer, io C, the fourh nmber is refsrred as
pcrl3l. Not€ thal, itr C couttirgofeleme s begirs with 0, and mt
L Tlrus. in this example perl3l rEfers to 23 and perl4l rcfers to 96,
rn general, the notatjotr would be perJil, where, I cao take a value
0.^1, 2. 3,-or 4, depe[ding on the positiotr ofthe elemenr b€iDg
rel'erred. Here per is rhe subscripted variable, whereas, I is it!
subscript.
A subscripted valiable is also calle.d atr .aEay'.
Thus, an a[ay is a
collection of similar elemsots. These similar el€m"ot"
"orfJ
6" ufi
Itrts, or all ,lorts, or all chrE, etc. Usually, the array of chrrs is
called a 'striag', wherras an aray ofitts o; tro.ts i" iaffea
"implyan array. Remembcr that all el€rne s of any givea array musibe
of the same tlTe i.e. w€ camot have e adat of l0 mmbers, of
which 5 are ltrts and 5 arp floats,
To begin with, like other variables m anay oeeds !o be declarcd,
so thd the cotrpiler will kaow wtat tind oim *ray -a m* iargJ
an afay we waat For exaEpla,
lnt ma*s[30] ;
Hcre, lnt specifies the Orpe of thc v{iablg just ss it do€s wirh
ordinary ya ables and thr word lnlrltl i! fhe trane ofthe vadable.
The aumb€t 30 tells how ooy elcorfias of th€ t p€ ht wil be;our array, This number is ofteo howu as .dimeogioa'
of the array.
Thc bractct ( [ ] ) trfh lhe coq,il€r that wc are <tealiag with m
To fix oul id€as, let us note &*,r a few facb 8boitt ar.ys:
(r) Aa anay is a collectio! ofsiDila. elcmerb. It is also knowr
as a subscripted variable.
(b) Before using an array its tpc ad size trust be d€clarcd. For
cxanple,
38
lnt arI3ol ;
M TIOOI ;
char ch[25] ;
(c) The ftlt elemsot io the aray is numbered
element is I less lhatr the siz€ ofthe aray.
Chapler 2: Pointers and -Arralt: r'l
num[] = i '
)
So do rem€rEber tha! ensudog that we do not rcach beyond
the array size is entirely the Eograxnmer's botheratioo and not
the compiler's.
Passing Array Elements to a tr'unetion
Army elements can be passed to a furctiotr by callitrg the furction:
(a) by value, i.e. by passitrg values of array elements to the
function
(b) by refercnc€, i.e_ by passiag addre*ses ofaray elements to the
function.
Programs showing how these calls atE made are given below.
l' Pto$am 12'l
f Demonstralion ol call by value
./
main0
(
intii
int ma s[] = ( 55, 6t 75, 56, 7S, 78, 90 ];
for(i=0;i<=6;{+})
display(mdksll);
l/
dlsplay ( int m)
(
printf ('h%d', m);
l
And here's tbe output...
0, so the last
(d)
1e) If we so itesiro an aiTay catr be itritialised at lhe same place
where it is declared. For exarple,
int num[6] = { 2, 4, '12, 5, 45, 5 } i
int n = ( 2, 4, 12, 5, 45, 5 ) i
ioat pressl] = { 12.3,342, -8.4, -11.3 }:
(fl Ifthe anay is itritialis€d wherc it is defind mentioning the
dimension of array is optiooal as in second oraqle above'
(g) If the army elemetrts a€ not givetr atry specific valucs, they
are supposed to cotrtaitr ga6age values
(h) In C therc is tro check to s€e ifthe subscript used for an array
exceeds the size of the dray. Dat e'ntered with a Eubscript
exceeding the array size will simply be plaoed in memory
ousiite tie anaft probably oa top of orher data dl ofl the
program itsetf. 'ifris witt load to uprcdiotable results, to 6ay
iheicast, anrt there will be no error messag€ to wam you that
vou are goilg beyond thc array size"In some cases the
iomputer rnay just harg. Thus, th€ following progam may
tum oul to b€ suicidal:
f ProgEm '11
'/
main( )
{
int num[40], i;
for(i=0:i<=100;i+|)
66
06
76
42 Understatding Pointers In C
Here, w€ arB passing ao individual aray el€inent at a time to the
tunctiotr dtsplay( ) aod getting it pdnted in the tunctior dtiplay( ).
Note that since at a time ody otre elemeot is being passed, in the
functiotr it is collected in a odirary integer variable m.
And mw the call by referenc.e.
f Prcgrarn 13'/
f Demonstralion ofcall by lefelence'/
main( )
(
inti;
ini ma s[] = { 55, 65, 75, 56, 78, 78, S0 } :
for(i=0;i<=6;i+)
disp (&m*s[ ];
)
disp ( int 'n )
t
pdntf ( "Vr.rfi', 'n ) ;
)
Atrd h€re's the output...
Chapter 2: Pointen and Arays 43
Here, we are passitrg addrcsses of individual array elements to the
functioo displsy( ). Herce, the variable in rphioi this addrcss is
collected (n) must be a pohter variable. And sitrce n contains the
address of array elemetrt, to pdtrt out the arrly element we must
use the 'value at address' operator (*).
Read the following p.ogram carefrlly. The pu4rose of the firnction
is to just display the arlay elernents on ihe icreea. The program is
only patly complete- you are required to *dte thi iraction
show( ) on yow olvtr. Try your hand at it.
/. Program 14
./
main0
{
int ij
int ma*sll = { 55, 65, 75, 56, 78, 78, 90 } ;
for{i=0li<=6;i++)
disp ( &marks[] ) ;
)
disp (int.n)
{
show (An );
)
Pointers and Arrays
To be_ able to see what pointers have got. to do with arrays, Iet us
first leam some pointer aritlmrctic. Consider the foiowing
example:
f ProgEm 15
*/
main0
{
int i = 3,'x;
floa1= 1.5, 1'
char k = 'c,,
*z
;
56
78
78
90
55
65
75
56
78
78
90
pdntf('Vtvalue oli= 96d", i);
pdntf (Walue ol j= %f, j);
pdntf (Walue of k = 9dc', k);
x=&i;
y=&j;
z=8*;
pdntf ( tnoiginal value in x = %u', x ) ;
prinf ( 1nodginal value in Y = %u'' Y ) ;
pdntf ( 'hodginalvatue in z=%tt,zli
pdntf ( lnvrNew value in x = %d, x ) :
printf ( 'hNew value in Y = %u', Y);
pdntf ( tNew value in z = %u', z ) ;
)
Suppose l, J and k are storcd itr mernory at ad&esses 1002,
and 5006, the output *,ould be...
Value ofi= 3
Value ofj= 1.500000
Valueolk=c
Original value in x = 1002
Original value in y = 2004
Original value in z = 5006
New value in x = 1004
New value in y = 2008
New valu8 in z = 5007
Chapt* 2: Pointers and Arrays 45
Observe the last three lines ofthe output. 1004 is equal to original
value in x plus 2, 2008 is equal to origitr l value in y plus 4, and
5007 is equal to original value in z plus I . This so happens because
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
incremented, it points to an addrcss two locatioos after the currgflt
location, since an int is always 2 b)rtes long. Sirnilarly, y points to
an address 4 locatiols after the cunent locatioa and z points I
looation after the cur€nt location. This is a very important result
and can be effectively used while passing ths etrtire array to a
function.
The way a pointer can be hcremetrte4 it can be deqemented as
woll, to point to ea.lier locations. Thus, the following operations
can be perfomed or a pointer:
(r) Addition ofa number to a pointer. For exarrple,
inti=4,'j,'k;
j=&i;
j=i't:
j=j*9;
l=j+3;
Subtraction ofa number Aom a pofuter. For example,
lnti=4,ti,'k;
x++;
y++ ;
2004
(b)
.8i ;
=i-5;
k=j-6;
word of caution! Do not atterEpt Ore fullorrilg operations
lnicrs,.. 0ley would nev€r wort out
Addition of two 1,oioters
Multiplying a pointer with a numb€r
Dividing a pofurter with a atutrbcr
Now we will try to corelate the following two facts. which we
have already leamt:
(a) Array elements arc always stor€d itr contiguous memory
locations.
(b) A pointer wben incremented alwalrs poitrts to an immediatelv
next location ofits qpe
Suppose we have an afmy,
int numl]= { 23, 34, '12, ,14, 56, 17 };
The following figure shows how this array is located in memory.
Chapter 2: Pointers and Anayq 4Z
pintf ('addrcss= %u', &numll) ;
i*j
)
]
The output ofthis program would be:
element no.0 address =,1001
element no. 1 addrcss = 4003
element no.2 addEss =,{005
elemenl no.3 addBss = 4007
element no.4 address = 4009
element no.5 addEss = 40'11
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
would be 2 b)'tes greater than its immediate Eedecess;r.
Our next two pograms show two ways in which we can access the
elements ofthis array. The fitst on€ uses the subscript notation.
f Pto$anj7 'l
main0
(
inl numl] = { 24, 3d, 12,44,56, 17 };
inti=0i
while (i <= 5)
(
printf ( 'naddrcss = %u ', &numfl ) ;
prjntf ( tlement = %d', numlil ) ;
l++ ;
)
Figure 2.1
Herc is a program that prints out the memory locations in which
the elemenls ofthis aray arc stored.
f Program 16'/
main( )
t
int nunll = 124,U, 12, 44,56, 17 | i
inti=0;
while (i<= 5)
{
printf ( elementno. 96d
.,
i ) ;
23 34 t2 44 56 t7
400 4003 ,1005 4007 4009 4011
48 Understanding Point*s In C
The output ofthis prcgram wottld be:
address = 4001 element = 24
address = 4003 element = 34
address = 4005 element =
'12
address = 4007 element = 44
address = 4009 demem = 56
address = 4011 elemenl =
'17
The next method accesses the array elemeDts using poioten
/'Program 18'i
main( )
{
int ntim[] = {24,34, 12,44,56, 17 };
inti=0,-j;
j = &numl0l ; f 6lign address o, zelofi elemenr
*l
while(i<=5)
{
printf ( 'haddrcss = %u ' , &numll ) ;
pdntf ( "element= 96d', I ) :
i++ ;
j++ ; f increment poinler b point lo ne* Iocalion '/
)
l
The output ofthe program would look like this:
address = 4001 element = 24
address = 4003 element = 34
address = 4005 element = 12
address = 4007 element = 44
addrcss = 4009 element = 56
address = 4011 element = 17
Chapter 2: Pointers and Atays 49
In this piogram, to begin with we have colleoted the base address
of the array (address of 0s element) in the va.iable j using the
statement,
j= &numlol; f assigns addr€ss,Oo1 b j'l
When we arc inside the loop for the first time j contains the
address 4001, and the value at tlds addrcss is 24. These are printed
using the statements,
pdntf ( address = %u ' , &numfl ) ;
pdntf ( "element = %d',I );
On inqementing j it points to the next mernory location of its O?e,
that is location ao. 4003. But location number 4003 contains ihe
seoond element of the array, therefore when the prltrtf( )
statements arc executed for the second time they pdnt out the
second element ofthe array and its addE$s (i.e. 34 and 4003). This
oontinues till the last element ofthe array has been p nted.
Obviously, a questioa arises as to which oflhe above two methods
rhould be used when? Acce$sing a.I:ray elemeds using poi
r!!!yq faClgl th!4 qno€ssftg lhein ljr subscripts. However, ftom-
lhc point of view of convenience inligramming we should
observe the following:
Anay elements sholld qe accessed using pointers, if the elements
t!!.19-!Eg!!!!99r4 a fixed order, sav &om be EiniGind. or
Cof end to besinnliE, or=-ry d temenr
rldfinite logic.
r lt would be easier to access the elementjfgilgj lubrDriptjfltrEre
,b@"u."
llrc, accessing the elements by pointeN would work faster than
r atr ltsc ripts.
Undersnnding Pointers In C
Passing an Entire Array to a F unction
Earlier we saw two programs one m which we passed individual
elemeds of an array to a firnctio4 and another io which we passed
addresses ofindividual €lernents to a funotion. Let us now see how
to pass the entile aray to the function rather tha[ individual
element.s. Consider the following exarple:
f Program 19'/
main0
t
int num[] = {24,3'1, 12,,14,56,17};
display(&numlol,6);
display ( int'j, int n )
{
inti=1;
while(i<=n)
(
Pdntf ('VElemenl = 9dd', l ) ;
i++;
j++ ; f increment poinbr b pointb next localion ?
)
)
Here, the dlsphy( ) frmctioa is us€.d to print out the array
elemeffs. Note that addre$s of the zcmth elsn€ is bciag passed
to the dlsplry( ) fitnction. The while loop is same as th€ oDe uled
in the eadier prograri to access lhe array elernents using pointers.
Thus, just passing.lhe address ofthe zeroth elemeDt ofthe array to
a furction is as good as passiry tbe entire aray to lhe firnctionr It
is also necessary to pass the total number ofelements io the array,
otherwise lhe dtuphy( ) fi.mctioo would not know when to
termjrEt€ tte vhlle loop.
Note that $e addrcss of the zercth element (often klown as the
base addrcss) can also be passed by just passing the name of the
anay. Thus, the following two function calls are same:
0qisplay(8num[0],6];
/isplay(num,6);
The Real Thing
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
thought. Once again coNider the followi[g aray.
4001 4003 ,1005 AOM 4009 4011
50
Figre 2.2
This is how we would declarE the above atray in C,
inl numll={23,34, 12,44,56, ,t7};
We alread_y, know tbat oa meotionilg the name of the array we get
its base address. Thus5 by sayhg raum we would be able to r*er
to the zercth clement of the arfif,-ilralTfZf GeraD-Easi[sEe
that *truE a+L1fl![.+ql!q!Lr€Gr !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,
num[il, the C compiler iatcrDally cotrv€{ts it to *( num + I ). This
mealts th.t all the followin€ ootatiotrs at€ !ame:
numliJ
'( num + i)
52 (lndersnnding Pointers In C Chapter 2: pointers and Arrays 53
l1
-ii+num)
ilnuml
And here is a prcgram to prove my poht.
f Pmoram 20 '/
f Acc-essing anay elements in difierent ways
ti
main( )
{
int numll = { 24, 34. 12,44,56, '17
} :
inti=0;
while (i<= 5)
{
pdntl ( address = %u ' , &numll) i
printf ( 'element = %d '. num0 ) ;
pdntf ( '%d ', '( num + i) ) ;
pnntf ( 'Yod ', '( i + num ) ) ;
printf ( 'Yod', ilnuml) ;
i++ i
)
)
The output ofthe program would look like this:
addrcss=400'f elerrefi.=z4 24 24 24
address = 4003 elemeot = 34 3}1 34 34
address = 4005 ehrnefi= 12 12 12 12
address = 4007 element = il4
'14 '14
44
address = 4009 element = 56 56 56 56
address = 4011 *n,e,rt= 17 17 17 17
More Than One Dimension
So far we have looked at arrays with only one dimensio[ It is also
possible for arrays to have two or more dimensions The two;
diftensional array is also called a mafix. Here is a samnle
progam rhal initialises a 2-D array and print, orai;.1".;"; ""''
f Prcgrcm21|'t
maino
{
int stud[s][2] = {
11234,561,
1t212,331,
{ 1431, 80 },
11312,78),
11203,751
);
int i, i;
for(i=0;i<=4:i++l
{
prjntf(h,);
,or(j= 0i j<= , j++)
pdntf('yod .,stud[m);
l
)
Look ar rhe pritrtf( ) statemelt...
printf ( 'Yod ', studlr[l ) j
11, "+lltt{]
fie trIsr subscripr is row nunber. The second
EuDscnpl te s wbich ofthe two colurDtrs arE we talking about... thi
11oth
c9tryn or_the frst colum- Rem€mber tfr"i".rrti'og oimws and columns begins witb zem.
Thc complete array arrangerneat is sho*n hlour
54 lJnderstanding Pointers In C
Chapter 2: Pointers and Arralts 55
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] ) ;
we expect the Od elemetrt to get priated aod tbe 06 elernent is a 1-
D anay. We know that just m€trtiodry a l-D array gives its base
address. Herce the printf( ) would print base ad&ess of the 0d l-
D anay. Similarly, stud[l] would give address of lr l-D aray and
so otr.
This fact can be illustrated by the fo[owing program:
.r Pl0onn22'l
. /f ReferfgurB 2.3 given in 0E pGvixBsectbn'/
Vl maino
Lt' in, rtuotsltzl= (
( 1234.56 ),
11212,331,
{ 1434, 80 },
{ 1312,78},
{ 1203, 75 }
];
inti,j;
for(i=0ii<=4;i+i)
pdntf ( "hAddress o, ,6d fi 1D any = l6u', ;, sM[l 1 ,
)
And here is the output...
Address of 0 th l-D aray = 4001
Figure 2.3
'I1rus. 1234 is storEd in stud[0][01,56 i8 stored iD studlollll and
t"
"o.
fnt above arraogcment highlights the hct that a-two-
dime[sional array i6 trothing but a collection of a number of one-
dimensional arrays plaoed orc after oother'
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
tfr"."
"*
no -tit *A cohoms' to memory whe&er it's a l-D or a
i-o
"r-y
At at-*ta are stolpd in one continuous chain'
Pointers and Two Dimensional Arrays
Catr we not tef€r elem€Dts of a 2-D afiay usitr8 poinlEr notatioil'
the wav wc did itr ooe{imeDsioDal anay? ADswer is y!s' only me
prociure is slightlv dimcdt to urderstand- t'et us see how'
The C language embodies e uousual but pow-€'rful capability: it
".n
treat pirrs of an anay as aEays' MorG 4ccifiGally' each rortr ot
,**"--a]i.*i"J
"t-i'
* & thought as a one-dimensioDal
arrav. Ihis i8 a very iEportaut fact if we wish to access aray
el#ents of a twodimersioul array using pohters'
Thus, fie declaration,
' int stud[51t2] ;
56 Undersnnding Pointers In C
Address of 1 th 1-o aray = 4005
Address of 2 th 1-D aray = 40 )
Addrcss of 3 th 1-D aray = 4013
Address of 4 th 1-D an-ay =,1017
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
of the 2-D array. Heoce the exprglgiorL4itud-+-0 L€iles tN the
ed.iress of Ge 0" elemeot of Ee 2-D aray. Naturally. lheadrl'ess of the 0d elemeot of the 2-D atay,
I element. But the Orh
elemefi ofthe 2-D array is a l-D aray- And on mentioning l-D
would givs base addtEss oft- l-D anay.
'(stud[2] + 1 )
'(-(stud+2)+1)
Using *ese concepts the following Eogram priDts out each
element of a two-dimensional aray using poirter notation.
f Pnlftn23'l
main0
(
int studl5ll2l = {
{ 1234, s6 },
11212,331,
{ 1434, 80 },
{1312,781,
{ 1203, 75 }
),
inli,jj
for(i=0;i<=4;i++)
t
printf("h');
for (j= 0;j<= 1 ;.i++)
. printf("70d','(-(stud+i)+j));
l
)
And here is the oiitput...
array we get its base address. Heqqg j(!]E4! jllLLtygqlhe base
addrcss ofthe 06 l-D array. Referring to Figure 2.3 this rums oul
io be 4ffiI:Timilady, caD you interpret the meaning of studlll
(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
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
array we get its base ad&€ss, *( stud + I ) gives base address of lsr
t-o,arravW))
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
ad&ess ,1009, the address of lhe second one-dimensional array.
Obviously ( ,1009 + 1 ) would give the sddEss 4011. Or
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 ).
But, we havc alncady mt€d wtilc learuing l-D &rays that numlll
1234
1212
1434
1312
.l203
80
78
75
is sam€ as r(E!n + l). Simi :( ttd[2] + l) ie same as,
6ffissions referio the
srtdt2ll1
Pointer to an ArraY
The way 1,,e cao have a pointer to atr integ€i, or a pointer to a float,
"u,
*" ulio have a pohter to an array? The answer is yes
Declaration of a pointer 1o atr array, however, is a little clumsy
For examole. the declaration Lrt ( *q
)l4l Eeans tbat q is a poitrter
,o on orr& of4 itrtegers. Let us use this pointer to an army in a
Eogram. Herc it is. . .
I Pmgram 24 '/
main0
{
iit alll4l= {
5,7,5, 9,
4, 6, 3, 1,
2,9.0,6
);
p=(int )a;
q=a;
pdntf ( 1n%u %u', p, q ) :
p++:
pdntf ( 1no/ou %u', P, q ) ;
)
whereas, q statts pointing to the text 1-D aray of 4 integers.
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.
almv to a
1,2,3,4,
5, 6, 7, 8,
9, 0, 1,6
int'p;
int ('q )l4l ;
And here is the output...
65500 65500
65502 65508
To begin {.ith both p and q contain the same address 65500'
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,
Passing 2-D Ariay to a Function
There are thtee ways in which we can pass a 2-D
function. These at€ illustrated iD the following program.
f Program 25 '/
f Three ways of accessirE a2-D a,ra(.'l
#include <alloc.h>
main0
(
int aB[ ]E_ {
);
clrsc( );
disphy (a,3,4);
show ( a, 3,4 ) ;
pdnt(a3,4):
)
display ( int 'q, in row ir[ col )
{
inti,j;
for(i=0;i<rcy;i++)
{
for (j = 0;j<col;i++)
Pnntf ('old',' ( q + i'col +i ) ) ;
printf('n');
)
60 Understanding Pointets In C Chapter 2: Pointers and Arravs 6l
1234
5678
9016
1234
5678
9016
In the displd ) ftactioa we have collected the base address of the
2-D array beiag passed to it in an odinary itrt pointer. Then
through the twoJor loops using the expression * ( q + i * col + 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
r[2] J3l- Let us see whe6er the expression * ( q + i * col + j ) does
grve thrs elemenr oihol Refer Figure 2.4 !o uDderstand this.
printf (1n' ) ;
)
show ( intfq)141, int roll, int col )
{
inti,j;
int'p;
lor ( i= 0; i< row;ir-i )
{
p=q+i;
for(j= 0;j<col;j++)
pdntf ( Yod ', ' ( p+j) ):
pintf (t');
)
prinlt('n');
)
pdnt ( i;t q[ ][4], int Dw int col ]
{
inti,ji
for(i=0;i<rorv;i++)
{
fq(J=0;j<cot;j+)
pdntr ( '96d ', q[][! ) ;
pdntf('Vr');
)
pdntf("h');
)
And here i$ the output. . .
1234
5678
9016
4001 4003 4005 4007 4OO9 40tt 4Ot3 4Ot5 4Ot7 4}tg 4O2t 4021
Figure2.4
l'he expression * ( q + t * cot + j ) becomes * ( 400f + 2 * 4 + 3 ).'l'his tums out to be * ( 4001 + ll ). Since 400I is address of an
inleger, * ( 4001 + tl ) tums out to be * ( 4023 . Value at this
oddress is 6. This is indeed same as e[2][3]- A more general
lbrmtrla for accessing each array element would be:
r ( base address + row no.
t no. o, columns + column no. )
ln the show( ) function we have defined q to be a pointer to an
lnay of 4 integers through the declaratiorx
(Jnderstanding Poinlers In C
int (.q )lal ;
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
int pointer, and then using lhis pohter all elements ofthe zercth I -
D alay are accessed. Next time thrcugh the loop when i takes a
value lf th€ exprdssion q + i fetches the address of tho first l-D
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.
In the third tunction print( ), the declaration ofq looks like this:
intqll[4]:
This is same as int ( rq )[4], vhere q is pointsr to an array of 4
irltegefi. The only advantage is that we can rrow use the more
familiar exEession q[il [] to acce$s array eleEreflts. We could have
used the sarne expEs$ion in show( ) as well.
Three Dimensional Arrays
Consider the following array declaration:
int a[3]l4ll2l = {
{
12,41,
{7,8 },
i3' 4 ).
i5,6 )
Chapter 2: Pointers and Atays 63
{2,3}
),
{
(8,e)'
17,21,
{ 3.1},
{5,1}
)
);
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,
each of whicb is a twodimensional aray of four rows. each of
which is a one-dimemional array oftwo elemehts. In other words,
a onedimeosiona!_array oftwo eleDents is constructed first. Then
four such ooe-dimeisional arrays are placed one below the other to
give a two-diDensional aray containing four rows. Then. three
such two{imeDsioD4 arays are placed ore behind the other to
leld a theedidensional aray containing three 2-dimensional
arrays. In the array declaratioo note how the commas have been
given. Following figune would possibty help you in visualising the
situation better.
xd 2-D Alray
tn 2-D kr.y
on 2-D Array
62
),
{
{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.
Figure 2.6
How would you reler lo the array element I in the above array?
The first subscript should be [2], since the element is in third two-
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
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.
Can we not rcfer to elements of a 3-D array using the pointer
notation instead of the subscript notation? Certainly. Let's first
begin with a simple Eogram-
/t Program 26
-/
maino
{
int aPl[3][2] = {
{
{2.41,
17.8'^).
{3,4}
],
];
printf ("n%u", a);
printf ( 'nolou',
.a
) ;
printf ( 'b%u', -a ) ;.
pdntf ( lno/od', *a
) ;
printf('ho/ou',a+1);
p ntf { 'n%u', 'a + I );kLprintf('h%u', *a + 1); '
printf {"n%d',
*a + 1);j .
)
Figue 2.7 shows the arangcment ofthe 3-D aray in memory.
Figure 2.7
And here is the output ofthe prografi...
.l04
t0r
t0{'
I
ilt
t0r
t0r
{2,2},
12.31,
{3,4}
06 2-D arlzy-+- t, 2-D array
21417 8 3 4 2 2 2 3 3 4
104 106 loa ll0 ll2 ll4 116 I18 120 t22 124 126
66 IJnderstanding Pointers In C
J
Referring Figure 2.7 it's not difficult to imagirc why the first
prtntf( ) pdtrts out 104. However, the outsut of second and thftd
pritrtf( ) is a little supiisiry. Let's try to undflstaod it
Each element ofa 3-D au'ay is a 2-D aEay. Once the 3-D aray i8
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
that on mentioning a 2-D array we get its base address hence the
second pri f( ) outputs 104. what about tfre exprEssion **e? *r
gives poiater to zeroth element of the 2-D an'ay, h€na€ **a would
give the zeroth eleme . But the zetdflr elernent ofthe 2-D aEay is
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
try to alalyse the output ofthe next prirtf( ) statement a gives the
aidr".r oi znroflr i-D arra% therefore, . + I would give the
addrcss of fiIst 2-D aray, which as per the fgure is 116. Can you
now imagine the output ofthe rcst ofrhe prhtf( )s? Try it.
),
{
Passing 3-D Aray to a Function
There are thrce ways i4 which we oatr puis a 3-D atray to a
function. These are illustrated below.
f Pmgram 27
./
f Three ways of passing a $D anay b funclixl '/
main0
(
int i, j, k;
jnt a[2]Pl[4] = {
{
1,2,3,4,
5,6,7,8,
9,3,2'1
2,3,5,7,
4,3,9,2,
1,6,3,6
]
);
clrcc( );
display (a,2,3,4 );
show (a, 2, 3,4 ) ;
print (a,2, 3,4 );
getch0;
)
display ( int
rq,
int ii,
'nl
ii, int kt )
(
int i, j, k;
for(i=0;i<ii;i++)
{
br(j= 0;.i<X; j++ )
(
for(k=0;k<kk;k+t)
pnnf ('%d','(q + i'jl'kk+ j'kl+ k) ) ;
printf ( 1ll" );
)
printf(1n');
)
pdnf ( 1n" ) ;
)
show ( inl (
-q
)Bl[4], irf ii, imii, int kk ]
(-
int i, j, k;
int'p i
for(i=0ji<ii;i+r)
t
for(j=0;i<ji;j++)
{
p =c[][];
for(k=0;k<kk;k+)
Pdntf ( '96d ', '( P
+ k) ) ;
printf( 1n' ) ;
)
printf('1n');
)
)
/ print ( int q[ ]l3l[4], int ii, inl ii, int kk )
"r'1
int i, j, k;
for(i=0;i<ii;i++)
{
forlj=0;j<ii;j++)
{
for(k=0;k<tk;k++)
pdntr ( %d '. q[]D[{ ) ;
pnff (l" ) ;
)
pnnf('1n') ;
)
)
And h€re is the output...
123 4
5678
932'l
2357
4392
1636
1294
5578
Understanding Pointers In C
Chapter 2: Pointers and. Arrays 69:
932'l
4392
IOJD
1234
5678
9321
2357
4392
'I 636
The wotking of lhis progre ir same as that of kogram 25
discussed earlicr. HeDcc all ftar I yrduld do here i,s explain how q
has been declared in each fimctiol
Table 2.1
Returning Array from Functiin
Now that we tnoq, how to pass a 2-D ot a 3-D aray to a firnotion,
let us find out how to r€tultr a,l array ftoItr a fuDotio[ Therc are
again three methods to aohieve this. Suppose we wish to retum a
2-D anay of integers from a function we caa rcfum the base
addrcss ofthe array as:
- A pointer to an integer
- A pointer to the zeroth l-D array
- A pointer to the 2-D aray
41lq )t3lt4l 'qis a poitrb to a 2-D snv of3 rows md 4 columns
iDt qt lt3l[4] q is a]6iqt€I ro a 2-D sray of3 rows ird 4 coluotrs
This is shovn in the followitrg ptogram. The firdctior futrl( )
reltrms the base addrcss as pointEr to integor, the function fuD2( )
rgturns it as pointer to zerolh l-D aray, whereas fun3( ) retums it
as pointer to 2-D array ofhtegeN. Note the prototype declarations
of the functioDs caefi ly.
f Prcoram 28 '/
I Th;e ways of lBtuming a 2-D aray tun a funclion
*/
#defne ROW 3
#defne COL 4
main0
{
int i, i;
tint'a;.
int'tun10:
int ( 'b )ICOLI;
iirr ('f,ii'20 )poll;
int
-p;
int ( 'c )lRowlpol-l :
int ('tun3( ) [RoWIcoLl ;
cllEc( );
a=tun10;
pdntf ( hAray allll in mai( ):W ) ;
lor{i=0;i<ROW;i+r)
l' for( i= o;i< coL:j+)
printf ('%d';'(ar i'col+ j )) :
pdntf(1r'');
)
setch( ) ;
b = fun2( ) j
printf ( "nArEy bl l[ J in main( ):h. ) ;
for(i=0;i<ROW;i++)
{
p=b+i;
for ( j= 0; j< COL 'i++ )
t
prjntf(t/od',.p);
p++;
)
pnntf ( "Vr') ;
)
getch0 j
c = tun30;
/
printf ( "h&ray d l[ I in mdn( ):W ) ;
for(i=0;i<ROW;i+[)
{
for(j=0'j<COL.++)
pdntr( %d., (.c)[ilUI) ;
pintf('rf);
)
getch0 j
)
Int.fun10
(
shlic int alRowlmrl = (
1,2,3,4,
5,6,7,8,
9, 0, 1,6
);
inti,i;
"2 Understaading Pointers In C
pintr ( lnAmy a[ [ I in tunl( )M );
for(i=0;i<ROIIV;i++)
{
tor (i = 0;i< COL 'i++ )
pintr ( 'r6d ', al i lli I ) ;
pintf( 1n' ) ;
)
retum(int.)a:
)
int ( 'tun20 )lcotl
{
shtic int blRoll'{mq = { .
9.4' 6' 4,
1,3'2'1,
7'5, 1'6
);
inti, j ;
pdntf ( tAray bt l[ I in tut2( )rtr' ) ;
for(i=0;i<Rqw:i+l)
{
tu (i= 0; i< col;F )
pintf ( *r6d
"
btilil );
pnntf ( t');
)
rctum b;
)
int ('fun3( ) )[Rou,tPOLl
{
static int ctRolfulcou = {
6. 3, 9, 'l'
2,1'5,7,
4,1,1,6
):
Chapter 2: Pointers and Arrays 73
inti,j;
printf ( 'hA;y cl II I in tun3( ):h' ) ;
for(i=0;i<ROW;i++)
{
for(j=0;i<COt;j++)
printr('Y!d', cl i ltj I ) ;
pdntr ( 1n');
)
retum ( int (' )[ROl'vllCOL] ] c ;
)
And here is the output- . .
Aray a[]llintunlo:
1234
5678
9016
Arlay al l[ ] in main( ):
1234
5678
9016
Anay b[][] in luo2( ):
9464
1321
Anay b[][]in main( ):
9464
1321
7516
Anay c[][]in tun3( ):
6391
2157
lJ"dntnndl!E!9!!!9o I" C
-
Chqtei 2: Pointers and Arrays Zj
4116
Aray c[ ][ ] in main( ):
63S'l
2157
4116
Returning 3-D Array from a Function
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
four possible *ays to do so would bG to retum the base address as:
- A pointq to ali integer
- A pointer to ihe zeroth l-D array
- A pointerto the zercth 2-D array
- A poitltcl to the 3-D ariay
Given below is the pDgram, which ifiplemeDts these four ways of
retuming a 3-D array.
f Program 29 '/
f Four ways of retuming a $D aray film a funclion
.l
*idefne SET 2
Itdefne ROW 3
#deline COL 4
maino
{
inti,j,k;
int'a;
int-fun'lO;
int (
.b
)lcotl ;
int ( 'tun20 ){coLl :
int ( 'c )lROaTCOLl ;
int ( 'tun30 )lRol'uporl;
int.p;
int ( 'd )lSEIllRoW[coLl;
int (
.fun40
)lsEr]lRovupoLl;
clrsc( )j
a = fun10;
pdntf ( lnAnay a[ I[ [ I in mai( ):W ) ;
for(i=0;i<SEI;i+i)
{
for(j= 0;i < ROW; j++ )
{
for (k = 0;k < COL;k+r,/
pdntf('96d','(a + ir RCIW'COt +j. COL + k )) j
printl ( 'h') ;
)
pdntf(1n');
)
getch0;
b = fun2{ ) ;
printf ( 'nAn-ay b[]Ull in mJn( ):h' ) :
fol(i=0;i<SET;i++)
(
p=(inl,)(b+i.ROlfl);
for(j= 0;i < Row;.1++)
{
for(k=0;k<COL;k+r)
{
pdntf ( '%d ., .p
) ;
p++;
76 Unilerstanding Pointers In C
)
pnntf (1n');
]
pintf('h');
)
ttro;
c = tun30;
pddtf ( 'nAray c[ ][ ][ I in main( ):W ) :
for ( i = 0; i< SEI; i++ )
(
p=(int')(c+i);
for(i=0;j<ROW i+t )
I
' for(k=0;k<COL;k+[)
{
pnntf ( '9{d ', 'P ) ;
p++;
)
pdntf ( 1n') ;
)
pnntf (l') ;
)
getch( ) ;
d = fun40 ;
p ntf ( 'hAray d[l[l[] in main( ):W ] ;
for (i= 0 i i< SET;i++ )
{
for (j = 0 ;j < ROI,V ;j++ )
(
Chapter 2: Pointers and Arrays 77
for(k=0:k<COL;k++)
pdntr('%d ', (-d )[i][i l[ k l);
pdntf ( 1n');
)
printf("n");
)
getch( ) ;
)
int. tun10
{'
inti,j,k;
static int alSEIllROVtIllCOLl = {
{
)
);
pdntf ( "hArmy a[ ]l lll in tunl( ):Vr' ) ;
for { i= 0 ; i< SET; i++ }
{
for (i = 0 ;j < ROW; j++ )
{
for(k=0;k<COL;k++)
printr { '%d ', ali ltj llk I ) ;
printf(ln'):
)
1,2,3,4,
5,6, 7, 8,
9,3,2,1
2,3,5,7,
.4,3,9,2,
't, 6. 3. 6
),
{
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,
int ( 'fun2{ ) )ICOLI 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'):
printf ( '%d ', bti[i]lkl]; )
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
)
);
printr ( "nAray d[ ][ ][ ] in tun4( )ln' ) ;
. for ( i = 0 ; i < SET ; i++ )
{
lor (j= 0;j< ROW jr+)
{
lor(k=0;k<COL;k++)
pintf ( '96d ", dliltjllkl);
pdnd(tu");
)
printf('Vr');
)
return ( int (t )lSEIllROWlcoLl ) d ;
)
And n"ere is the output...
Aray a[][][] in tun10:
123 4
5678
9321
2357
4 392
1636
Aray a[][][] in main( ):
1234
5678
932'l
2357'
4392
1636
Anay b[I][Iin tun2( ):
9464
1321
75't 6
6391
2157
4116
Anay b[][][jin main( ):
9464
'1321
7516
6391
2't 57
4116
Anay c[]ll[]in tun30: ,
3185
0652
2016
7 327
1423
0106
Aray c[][][]in m;in0:
),
{
3, 1,8, 5,
9, 6, 5, 2,
2,0,1,6
7,3,2,7,
1,4,2,3,
'9,
1,0, 6
i
82 Understatding Pointers In C Chapter 2: Pointers and Arrays 83
3185
9652
2016
7 327
1423
9106
Aray dll[]ll in tun40:
1705
2391
5116
cJ I /
1423
Anay d[][][]in main( ):
1705
2391
5116
5317
1423
7 216
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
but a colleclion ofaddrEsses. lae adclresses preselrt in the alray of
pointers oan be addresses of isolated variables or addresses of
array elemerfs or any other addresses. All rules that apply to an
ordirDry array apply in toto to the array ofpointeN as well. I think
a prograrn would cldiry the concept.
f Pmgram 30
.i
main( )
{
int 'ar[4] ; f fiay of inhg€r poinbls '/
int i= 31, j= 5, k = 19, t= 7t, m
.
an[0] = Ai;
an[1] : &.i '
anl2l = &k;
art3l = &l ;
for(m=0;m<=3;m++)
pdfltf ( 'h96d', '( adml) ) ;
)
Arld here is the ou&ut...
31
5
71
0'
kl
l-,,1 l--;l l--rl l=-l4008 5116 6010 7I l8
ad01 adll a"IL2I
4008 5116 60lb )r ra
7602 7@4 7@6
ant3l
Figure 2.8
Understanding Pointers In C
Figure 2.8 shorns the contents atrd the arangement of the array of
pointeN in memory. As you cal obwrve, arr contains addresses of
isolated lDt variables i, J, k and l. The for loop in the plog1am
picks up the addresses present in arr ard pdEts the values prcsent
at these addresses.
An array of poiaters can evetr contain the addresses of other
arrays. The following plogram wouldjusti! tltis.
/' Pogram 31 '/
maino
t
static int all = { 0, 1, 2, 3, 4 };
shtic int'p[] = {a, a + 1, a +2, a +3, a+4 };
printf ( ln'/ou %u 96d', p, 'p, '( 'p ) ) ;
)
I would leave it for you to figurE out the output of this program.
An array of point€rs is very popularly us€d fol sioring several
strings in manory, as you would see in tlre next chapter'
Dynamic Memory'Allocation
Coosider the array declaratioi,
int ma*s[100];
Such a aleclaEtion would typically be used if lqoinldent's marks
were to +e stored itr memory. The moment we make this
declaration 200 bytes aIe rcseped in memory for stoling 100
integers in il HowEver, it may so happen that when v/e actually
run thd program. we might be inteEsted in storing only 60
student's marks- Even in this case 200 bytes would 8et reserved in
memory, which would result in wastage of memory.
84 Chapter 2: Pointers and Arrays 85
Other way rouad there alwa]rs exists a possibility that when you
rrn the program you Deed !o store more ihatr 100 student's marks.
In this case the aray would fall short in size. Moreover, llpre is no
way to inqease or decrease thqauay size-dudng-crGeq![q4-!t][ the
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
rhe dme of executioo? This -is datrc__Jsl[g* standard [trary
furctions mill^.( ) and catloc(J. Since these tunotioos allocate
memory on the- fly (during executiotr) they are-oftentno",t1 as
'Dyramic meinorjr allocation functions=) L6t us now see a
program, which uses the corccpt ofd)mamic memory allooation.
f Program 32
ti
#incude ?lloc.h'
main0
{
hl n, avg, i,-'p, suo = 0;
pintf ( Enter tle number of studenb ' ) ;
scanf('%d', AD);
I p : ( imr) rnathc ( n | 2 ) ; ly
ir(P==xuLLl
---
{
pinu ( 'h lemory allocaton unsuccessqE) ;
eit( ) :
)
for(i=Q;ifn;i++)
scanf ( "96d', (p+ i));
for(i=.0ii<nii++)
sum:sum+.(p+i);
avg=sum/o;
printf ( "A .......ge mafts
=%d',
aW ) ;
86
e 4arks. Not a byte more, not a b,'te
integgr pointsr.p. Sfuce mr[oc( ) Etums a void pointcr we have
t r""ur[a it into aa integer poiorer. lo Ee first for looE-!!]iIJ
ti-"ii6-i"ttt aritlrne6rcwe tave storrd the marks ent!:red from
keyLoar{ulqlhe rn.-ory
-that
h* b""n allocated. In the tecond
for loop-we have 4ccessed the same values to fitrd the avemge
marks.
The calloc( ) functioos works exactly similar to Erlloc( ) except
for the faot that it needs tw-o atguments. For example,
inl'p;
p= ( int') calloc ( 10, 2 ) ;
Chapter 2: Pointe$ and Arrq)s gZ
Solved Problems
IAI What will be the ouFut oflhe following progiams:
(1) main0
(
int a[] = { 10, 20, 30, 40, 50 }
.
intj;
tor (j =p ;j < 5;j++ )
t/ printf('hyd.,t);
a++;
)
)
O tput
Emr message: LvaftJe tequirEd in fundfun main
Explanation
,Here, we have fiIs! asked- for the number of studelEwhose-4alks
are tgbe eltqed-ard lhelalloqated 9ub/-"1-qt!ch rnemory as is
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
address. Therefore, firsltt!rc flrcugh the loop; the Dritrd( )differeDce between mdto( ) and crnoc( ) is tbat' by defaulrlllhe address. l[erelore, trslttll! though the loop; the pritrtf( )
should print the value at this-bae€ ai[li&-s.-fr;iE ls nomemory Sn co
oat attocatea ty dtoi@s' s11 :Ers. wA& u!!g thrse problem up to this. The @ ies ln tEe oext statement,
an allav-
the only thing thai it l€rnembers about an array oace declared
ii"i""-i-r.",*.*d 6^ tr" GpnFit-*"
begimiggof-*c'@lgaur.
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. .
88 Understanding Pointers In C Chapter 2: Pointers and Arrays 89
(2) maino
{
foat all = { 13.24,1.5,1.5,5.4,3.5 };
ioat l, 'k;
1j=,;k=a+d;
j=j'2i
k=kl2',
printf ( 1n%f%1, 'j, 'k ) ;
I
Olttpu,
Eror message: lllegd tse ol Finler in tunction main
Explatatiott
i atrd k have b€en declared as pointer vafiables, wbich would
contain the addx€sses of foats. In otler words. j and k are
Iloat poinlefs. To b€gitr with, the base addrcss of the array
al I is stored io j. The ner(t statement is perfectly acceprablel
flr.
"aaress
offte 46 trort fiom lhe base addrEss is storcd in
k. The next t$'o stat€rne s arc €rroneous. Thrs is because the
only operations lhat can be performed oa pointers are addition
and subtaction Multiplication or division of a pointer is IIot
allowed. Hence lhe error message.
main0
{
nlol = 100 ;
nl24l = m0;
pnnf (t%d 96d',
-n,'( n + 24 ) +'( n + 0 )) ;
)
Outpat
100 300
Explanation
n[ ] has bein declared as an array capable of holdirg 25
elements [umbered ftoln 0 to 24. Then-100 and 200 are
assigned to n[0] and r[Zl resp€otively. Thetr comes the most
impolant pa
-the
prhtf( ) statemed Wheaeyer we
mendon the name of the array, we get its base address (i,e.
address of lhe zercth elqlre of the array). Thus, *n would
give the value at this base addness, which itr this case is 100.
This is theD prhted out. Look at the rcxt expression,
-(n+24)+'(n+0)
n gives the address of the zeroth element, tr + I gives the
address ofthe next el€rtre ofthe array, atrd so on. Thus, n +
24 would give the address-ofthe last elemetrt ofthe array, and
therefore *( n + 24 ) wonld give the value at this ;itdress,
which is 200tu our case. Similady, *( n + 0 ) would give 100
and the addition of the two *,ould result hto 300, trhich is
outputted nexl
main( )
{
int b[] = { 10, 20, 30, 40, s0 };
int i, 'k;
k =&b141-4; .
for(i=0;i<=4;i++)
{
pnntf ( 'Yod ', 'i( ) ;
k++;
(4)
(3)
90 Understtnding Pointers In C Chapter 2: Poinlerc and Arrays 91
Output
10 20 30 40 50
Expldnatio
Fi$t look at Figue 2.9. The aEay elements are stored in
cotrtiguous memory locations ard each element is an integer,
hence is occupying 2 locations.
Figure 2.9
The expression &b[4] gives the address of b[4] (4010 in this
oase)- From this addEss ifwe zubtract 4, we get 4002 Or did
you expect to get 4006? Remember that by subtracting 4 fiom
4010 what ltre mean is ge ss ofan integer, which is
4 integeE to the left of the integer whoG-addii:ss is 4010.
No$r', address of the i teger, whibh is 4 htegers to the left of
the irteger whose addrcss is 4010, is the ad&ess 4002 This
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
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
tlrough th€ for loop *k would yield the value at address
contained ia k, i.e. value at the address 4004, which is 20'
Similarly, rhe loop priots out the Iest of the elements of the
altay.
{5) main0
{
char a{l = "Visual.C++' ;
char'b = 'Visual C+' ;
printf('no/6d %d', sizeol ( a ), sizeof (b ) );
pdntf ( 'ln96d 96d', sizeof ( 'a ), sizeof ( 'b ) ) ;
)
Output
11 2
11
Explanation
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
b)4e.
main0
{
f Assume arEy begins at addess '1200
'/
int anll = {2,3,4, 1,6 );
pdntf ( '%u %d', an sizeol ( ar ) ) ;
)
Output
1200 10
Explanati6n
there is a'0'sitting at the end. b is a pointer h-ce its size ;" I
b)ts-5 atld *b both yield a charactei'V', whose size is one
(6)
b[0] btu bt2l bt3l bt4l
4lnm 4n0/. 4006 4008 4010
l0 20 30 40 50
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
elemetrts. each of2 bytes, sizr ofthe array is reponed as l0
bltes. Note thal except when used with sizeof( ), name of the
array yields its base address.
(7) maino
{
f Assume a.ray begirE at addEss 65486 '/
intar{l= { 12,14, 15, A,45};
pdntf ('%u %u', ar, &ar); 6printf{'%u %u'. ar+ 1. &ar+ 1):'t
)E-
Output
65466 65486
65488 65496
Explahalion
Both arr and &.rT yield tire base addless of the array.
However, rrrtl gives 65488, i.e. the address of the next
integer. However, &rrr + I gives 65496, i.e. the address of
the next array ofs inl€gers.
(8) maino
{
I Assume array begirE at ddless 65472 '/
int al3il4l = {
1,2,3,4,
4,3,2,1,
7,8,9,0
)'
pdntf ('h%u%u',a+ 1, &a+ I ) ;
)
Outpat
65480 65496
bqlafiation
Name of a 2-D arr.ay always acts as pofuter to the zeroth
element of the aray. Since the zeroth element of our 2-D
aray is l-D array of4 inlegers, a acts as pointer to this zeioth
1-D aray. Hence a+l gives us the ad&ess of the next l-D
array, i.e. 65480.
The expression &a + I yields 65496. i-e. rhe address of the
next 2-D array of 3 rcws and 4 columns.
(9) maino
{
f Assume array begirE at locdion '1002'/
int a[3][4] = {
1,2,3,4,
5,6,7, 8,
9, 10,'11,12
1;
printf ("Vt%u %u %u', a[0]+ 1,'( a[0]+ 1 ],.('( a +0 )+ 1 ));
)
- Output
1004 2 2
Explanation '
9594 Understanding Pointers In C Chapter 2: Pointerc and Arrays
A 2-D airay is a coll€ction of several l-D arrays. Name of a
2-D aray always acts as pointer to zeroth elemeat of the
almy. Hence, a acts as pointer to the zeroth l-D aray.
The expression r[0] + I is hterpreted by the compiler as *( a
+ 0 ) + l. This is same as *a +1. The expression *a gives
1002. Thercfore, *e +1 would give the address of the next
integer, i.e. 1004. Since a[0] + r yields 1004 *( a[0] + 1 )
would yield lhe value at address 1004, i-e. *( al0l + 1 ) can
be expanded gs *( "( a + 0 ) + I ). Hence, both the
expressions would yield the salne result, i.e. 2.
(10) main0
{
int al3l[4] = {
1,2,3,4,
4,3,2,8,
7, 8,9, 0
);
int'pf;
ptr = &a[o]pl ;
lun ( &pt ) ;
)
tun (int *p
)
{
printf ( 1nyd', 'p ) ;
)
Output
1
Explanation
Here, in ptr we bave stored address of l. Then we have
passed ad&ess ofptr to fun( ) and collected it in a pointer to
an itrt pointer- Dereferencitg this pointet yields l.
('11) maino
{
f Assume a.ray begins at location 1002 */
int a[2]Fl[4] = {
(
1,2,3,4,
5, 6, 7, 8,
9,1,1,2
),
{
2,1,4,7,
6,7,8,9,
0.0.0.0
)
I'
prjntf ( i%u %u %u 96d', 4
*a, *a, *a ) ;
)
Output
1002 1002 1002.'l
Explan .tio.,
- The expressions a, "a,
*ra, would give the base addrcss, i.e.
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
(12) main( )
97
{
int a[]= { 2,4,6,8, 10 };
int ij
for(i=0;i<=4;i+t)
{
'(a+i)=a[]+ilal'
printf('%d',t(i+a))j
)
)
Output
4812 1620
Explatation
Imbibe the following three frcts and the program becomes
very simple to undeistaud:
- Mentio ng the name of the array gives the base address
oI the array.
- AIIay elements arc stored in coDtiguous memory
localions.
- On adding I to the address of an integer, we get the
address ofthe next i[teger.
Wilh rhose factrs clearly laid out- let us oow try to undeNtand
the program. Remember that infemally C always acoesses
an:ay elements usi[g pointers. Thus, when we say a[i],
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
+ i ) is same as *( i + . ). Therefore a[il must be same as i[al.
Thus a[i]. *( a + i ), *( i + a ] and ilal refer to rhe same
element lbe ih element from the base address.
Therefore, the expressior used in the for loop, *( a + i ; = a111
+ ilal is nothing but alil - alil + alil- Thus all that is done in
the for loop is, each aray element is doubled and theD printed
out through printfo.
(13) main0
t
int alsl = { 2, 4, 6, 8, '10
};
int i, b= 5;
for(i=0;i<5;i++)
{
f (alil, &b ) ;
pdntl { 'h%d 96d', a0. b ) ;
)
)
f (int x, inl
-y
)
{
x=*(y)+=2;
)
Output
27
49
6 11
813
10 15
llxpldhaaon
After initialising the array when the control enteN the for
loop, the fimction f( ) gets called with value of a[i] and
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
(14)
evaluated fiIst and thell the Esult of this expression is
assigned to x. The first time thmugh the for loop *( y ) gives
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
f( ), b's value keeps getting updated, whereas therc is no
change iD the values of the array elemenh.
Figure 2j10
main( )
{
int alsl = { 2, 3, 4, 5, 6 };
inti;
change (a );
lor(i=4;i>=0;i-)
pintf { 'Y"d ', a[]) ;
)
change ( int'b )
{
inti;
for(i=0;i<=4;i++)
t
'b='b+1;
b++;ri
)
)
Output
76543
Explsnation
Figue 2.1I
While caling charye( ) we are passing the base address ofthe
aray, which as per Figure 2.ll is 4002. This address is
collect€d in b in the functioo change( ). Then the oontrol
enters the for loop, where we meet the explession *b = *b +
1- This means rcplace the value at the address contained in b,
with value al the address contained in b plus 1. Every time
b+ is executed, the address ofthe trext integer gets storcd io
b. Thus, using the address stored in b, we get an access to
aray elements that are now changed to 3, 4, 5,6 and 7. Oce
the control comes back from change( ), the current array
contents are then printed out ftom end to begindng through
the for loop.
401
E
f , I
b
l-5 I
4008
atol alll al21 a13 441
4co2 4004 4M ,1008 4010
bb
[ 4oo, I b--,[ 4oM I
100 Understanding Pointers In C
(15) mainO
{
int arll= {0, 1,2,3,4 };
int,pb;
for ( ptr = &ar{01 ; pt <= &ant4l ; ptr++ )
printf ( '%d ', tpr
) ;
)
Output
01234
Elplanation
Refer to Figue 2.12 lot a better utrderstanding of the
pIOgram.
Here ptr has been dectared as an integer pointer, i.e a
variable capatle of holding the address of art integer. In the
for loop, irl the initialisation part, this ptr is assigned the
address of the zeroth elernent of the integer aEay Suppose
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
for loop, the address storcd h ptr is compared with the
addrcss of the foufh aray elemen! i.e. 6012. Sirce for the
first time lthe, conditioa is satisfied (shce 6004 is less than
6012), the'cotrtsol reaches pritrtf( ) where the value at address
6004, i.e. 0 gits pinted. After executing priutf( ) the control
reaches pff+, where ptr is incremented such that it contains
the addrcss ofthe rext integer. Since the next integer is stored
at 6006, pf now contains 6006. Once again the condition is
tested- Since 6006 is also smaller lhar 6012, the conditiofl is
satisfied honce the printf( ) prints out the value at 6006, i.e. l.
And then pffi is executed again so that it corltains the
Chapter 2: Pointers and Arrays 101
address of the next iateger, i.e. 6008. This prccess cotrtinues
till all the array elements have beea prioM.
arrl0l arrlll alll2l .Irl3l arltll
0 I , 3 4
6008 6010 6012
ptpts
f eoor I o*, frooo I
FigtuIe 2.12
(16) main0
(,
int arl l= {0, 1,2,3,4};
int i, 'ptr;
for (pb= &ar40l, i= 0; i<= 4 ; i+| )
prinf ( %d ', ptfl ) i
)
Output
0123 4
Expla atiol .
In the initialisation part ofthe for loop, multiple initialisations
are being done. Fi$tty, ptr is set up vith the base address of
the alIay and then i is set to 0. Since 0 is less than 4, the
condition is satisfied for the first time atrd the control reaches
printf( ). Here the value ofthe exprcssion ptr[iJ gets printed.
102 Understanding Pointerc In C
Now ptrlil is nothiDg but r( ptr + i ). Sipce ptr coDBins tle
base address of the arr6-ylptu t I ) would gi-E the address of
the id irteger 8om the bas€ ad&ess. Since i is going to vary
fiom 0 to 4, this would give addrcsses ofo", l''.2"o. 3'o and
46 integers ftom the bas€ addE$s of the aray. Naturally, the
exFession *( ptr + i ) would give values at these addrcsses.
Thus, the for loop would print out all the array elements.
(17) maino
(
int anll={0,1,2,3,4};
inl i,
*p
;
for( p = ar, i = 0 ; p+ i <=ar+4 ; PF[, i+r )
Pdntf ( '96d ', '( P
+ i) ) ;
)
Output
.024
Explanation
The following figul€ would help in understanding the
program.
Chapter 2: Pointerc and Arrays t03
the initialisation part, p is initialised to trc base address of the
array. whereas i is initialised to 0. Afier these inirialisations
the cortrol rcaches the conditiotr. The condition is a little
complicated so let us isolate it for a clearE u[derstanding.
p+i<=alr+4
Here + enjoys a higher priority thar <=. Therefore, firct p + I
afld arr+4 arc performed ard then tha <= goes to work. p+i
yields 6004. wherEas arrH evaluates to 6012, SiDce 60Oa is
less than'6012, the condition is satisfied and fte coIlhol
reaches pr-intf(-), where value at ( p+i ), i.e. 0 gets printed.
Thed the control r€aches the iacrernentation part of the for
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.
Since the condilioo oDce again gets satisfie4 thi priut( )
pnnts out the value at ( p+i ), i.e. 2. Similarly, next time
around 4 gefs printed aud then the corditiol fails therefore the
execution is terminated
main0
t
int an[]= {0, 1,2,3,4};
int'pt;
for ( ptr = an+4;pt'>=ar; ptr- )
pdntf ( 'ol'd ', 'pf ) ;
Output
43210
Explanatioh
(18)
arrtol al'0l ard2l ad31 aq[a]
6004 6006 6008 6010 6012
0 I 2 3 4
Figure 2.13
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
Output
43210
The following figure would lead to a better understanding of
the program.
a'I[0] ar{ll ar[21 arrt3l an[4]
6010 6012
Dts PE
I rorz I PE-- -l eoro Il-l
I0 2 3 4
Pignrc 2.14
In the initialisatiotr part, ptr is assiFed the address of the last
element in the array. This is because rrr+4 gives the addrcss
ofthe fowth iateger Aom the bas€ ad&€$s. First time tbrough
the looD the cotrditiotr evaluates to true, siDce the addless of
the fourtlh elemeot (6012) would certainly be bigger thaD the
base addrEss (60M) of the array. Next, the conbol reaches
prhtf( ), wbi;h prints oltt the value at adiiress cortained in
;tr. i.e. "lue at addr€ss 6012. N€xl, the statement ptr- gets
executed which reduces pk io 6010. Sirce 6010 is also bigger
thar 6004, rhe condition is satisfied onoe again, ard the valu€
at 6010 gets printed through the printf( ). This process is
lepeated for all the aray elcments.
main0
{
int arll = {0,1,2,3,4 };
inti,'pf;
for(pb=ar+4, i =0: i<=4 ; i*)
printf (
"t6d ', Pt[-il) ;
)
Explanatio
ar{01 a{tl aEl2l an[3] . a44l
60M 6006 6m8 6010 6012
0 I 2 3 4
Figure 2.15
The above figule shows the amngement ofthe array elements
in memory-
In the iiritialisation part ofthe for loop, ptr is assigned a value
6012, since arrH gives the addrEss of the fouth integer Aom
the base address of the array. Here, the variable I is also
initialised to 0. Siace th6 condition is satisfied for the first
time (i being 0), the printf( ) prints out Ore vatue of ptr[-ll.
But what is ptrl-il? Nothibg but *( ptr - t ). And since i is 0,
*( ptr - i ) evaluates to *( 6012 - 0 ), i.e. 4. Then the control
reaches i+ where i is incr€rnented to l. Nexg the condition is
checked atrd sirce it evaluafes to true, the prini( ) pritrts out
the value of pfr[-il. Since this time i is l, ptr[-i] becomes *(
ptr - I ), i.e. *( 6012 - 1 ), i.e. * ( 6010 ). Thus rhe value 3
gets prinred. Likewise, 2, I ad 0 also get printed subsequent
times though the for loop.
main( )
{
int anlj= {0, 1,2,3,4};
int
tptr
i
(1e)
(20)
106 Understanding Pointers In C
for ( ptr = ar + 4 ; p&>= ar ph- )
. pdntf('%d ', ar Ipr- ar]];
)
Output
3210
Explanatiort
A picture is worth a lhousaDd words. Going by lhis dictum.
the follolving figure should add clarity to your understanding
ofthe pmgram.
Figue 2.16
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
Aom the base address. Since this address is gre.ter than tie
base addrcss, the condition is $alisfied and the control reaches
pritrtf( ). What does rrr I ptr - arr I evaluate to? ptr - arf
means 6012 - 6004 which yields 4 and hence arr[4] prints
out the fou h element ofthe array- Then ptr- reduces ptr to
6010. Since 6010 is greater than the base address 6004, the
condition is satisfied and once again the conhol reaches the
printf( ). This time ptr - {'r'becomes 6010 - 6004, i,e. 3.
Thus arr[3] pdtrls out 3. This pmcess is repeated till all the
integeft ill the array have been p.inted out
Chapter 2: Pointers and Arrqts 107
Possibly an easier way of understanditrg the expression ptr -
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
logical 10 expect the result ofthe subtraction as 4.
(21) main0
t
static inta[]= (0, 1,2,3,4 ];
static int'p[] = {a, a + 1, a + 2, a + 3, a + 4l ;
int
.'ptr : p;
printf ( "h%u %d", a, 'a ) ;
printf ( 'olou %u 7d', p, 'p, *p
) ;
pintf { ln%u %u %d", ptr, 'ph *ptr
) ;
Output
6004 0
9016 6004 0
9016 6004 0
E,Vlanation
Look at the initiatisatior of, the array p[ l. DuriDg
initialisafion, the addresses of various elemenis oi th"
".r
i
a[] are stored in lhe aray p[ l. Sioce the array pl 1 contalns
addresses of idegers, it has been declared as
-ari
arrav of
pornters to integers. Figue 2.17 shows the conteats of arrays
a[ ] and p-[l In the variable ptr, the base addrcss ofthe ariay
p[ l, i.e- 9016 is storad. Since this address is the address of
p[0], which itselfis a pointer, pti has been declarcd as pointer
to an integerpoi[!er.
Let us undelstand the first pritrtf( ) rcw.
T.
adoi arIlli anl2l alrt3] artal
0 2 3 4
6006 6008 6010 6012
108 Unilerstaniling Pointers In C
printf ( "hy"u %d', a, 'a ) ;
It prhts out the base address ofthe array a[ ] and the lalue at
this base address.
a[0] atll al2 431 {al
6004
p[01
6006
ptu
6008
pql
6010
pt31
6012
pt4l
60M 6006 6008 6010 6012
9016 9018 90m 9022
prr
lg0'61
7888
0 2 3
Chapter 2: Pointen and Anays 109
Now onto tlle last printf( ).
pdntf ( 'n%u %u 96d', pr, 'pr,
*ph
) ;
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
address 60M, which is 0.
(22) maino
{
static intalt = {0, 1,2,3,4 };
sbtic int'pU = {a a + 1, a +2,a+3,a+ 4};
int
*Ptr
= P'
ptr++j a}
pirfff ( 'n96d 96d j6d', pr - p, -pr - a,
*pb
) ; '
'Ptr++'
printf ( 1n9{d %d 96d', pr - p, 'p[ - a, 'p[ ) ;
l++ptr;
pdntf ( 1n%d 9(d 9{d!, pr - p, -pr - a,-ptr ) ;
++.ptr;
pdntf { %d 96d 9{d', pb - p, 'pr - a, 'pr } ;
)
Outryt
111
222
344
Explanation
Figure 2.17
Looking at the figsre, this u'ould turtr out to be 6004 and 0'
when you execute the p'.ogram' the address may tum out to
be somethfug other than 6004, but the value at the address
would be surely 0.
Now look at the second Pritrtf( ).
pdntf ( 1n%u %u 96d', P, 'P,
*P
) ;
Here p would give the base address of the aray p[ l, i e'
9016; *p would give the value at this address, i.e 6004; **p
would give the value at the address given by *p, i.e value at
addrcss 6004, which is 0.
110 Undentanding Pointers In C Chapter 2: Pointers and Amays 111
work and increfienls value in ph to 9020. Now with ptr
containing 9020, let us once again analyse the expressions ptr
- p, *ptr - a and **plr'- . -
Figure 2.18
plr-p
Figure 2.18 would go a loag way in helping us to understand
this prograno-
Herc ph has beetr declared as a pointer to an integer pointer
and assigoed-t[e base address of the array pt ]. which has
been declared as an array of integer pointers. wllat happens
when ptr+ gets executed? ptr lgiots ro the next inGger
pornter rp the armv pll. b other words. now btr adfiIdin. tfia-
adclress 9(r18. Now let us analyse the meaning ofplr _ p. *ptr
- a and r*ptr.
pk-p
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 - iis reducedto ( p + 1 - p), which yields l.
tptr
- a
*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 epression
become,s ( a + 1-.), which is nothing but l.
ptr conlairs 9018, so *ptr yields 6006. and hence *+ptr
becomes *( 60116 ), which yields I -
Thus tbe ouPul ofthe firsf prhtf( ) becomes I I L
Take a deep brealh atd then begin u,ith rhe analysis of*pt ++. Here * and r+ both are unary operalors. Since --
occurs aller the vadable, + would be dode later. Firstlv
*(9018) is perturmed, but since this value is not beini
assigned to any vafable it gets ignored. Next, ++ goes ti
401 altl at2 at3l al41
0 I 2 3 4
6004
ptol
6006
ptll
6008
Pl21
6010 6012
pt3l pt4l
6004 6006 6m8 6010 6012
9016 9018 9020 9022 9024
(
ptr ptr l
f noro I ,'*',ft"l I7888.
pts
7888
ptr
f,file"t-f,mtl7888
PF
7888
pts
llqo2o I .**ro,l-eo2tl
7888
pE ptr
f ,Ell *-pt',fG7l .@bt"
?888 78BB 6012
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition
Under standing pointers in c 3rd edition

More Related Content

What's hot

C interview questions
C interview questionsC interview questions
C interview questionsSoba Arjun
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Dushmanta Nath
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c programRumman Ansari
 
Complex C-declarations & typedef
Complex C-declarations & typedefComplex C-declarations & typedef
Complex C-declarations & typedefSaurav Mukherjee
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constantsCtOlaf
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in CShivanshuVerma11
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
Chapter 13.1.8
Chapter 13.1.8Chapter 13.1.8
Chapter 13.1.8patcha535
 
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1tanmaymodi4
 

What's hot (20)

C interview questions
C interview questionsC interview questions
C interview questions
 
C pointers
C pointersC pointers
C pointers
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Pointers In C
Pointers In CPointers In C
Pointers In C
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
 
Pointers
PointersPointers
Pointers
 
14 Jo P Feb 08
14 Jo P Feb 0814 Jo P Feb 08
14 Jo P Feb 08
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Complex C-declarations & typedef
Complex C-declarations & typedefComplex C-declarations & typedef
Complex C-declarations & typedef
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Adobe
AdobeAdobe
Adobe
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Chapter 13.1.8
Chapter 13.1.8Chapter 13.1.8
Chapter 13.1.8
 
Pointer in c
Pointer in c Pointer in c
Pointer in c
 
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
 

Similar to Under standing pointers in c 3rd edition

Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...SANTIAGO PABLO ALBERTO
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docxJoeyDelaCruz22
 
A TUTORIAL ON POINTERS AND ARRAYS IN C
A TUTORIAL ON POINTERS AND ARRAYS IN CA TUTORIAL ON POINTERS AND ARRAYS IN C
A TUTORIAL ON POINTERS AND ARRAYS IN CJoshua Gorinson
 
Arrays and pointers
Arrays and pointersArrays and pointers
Arrays and pointersKevin Nguyen
 
chapter-11-pointers.pdf
chapter-11-pointers.pdfchapter-11-pointers.pdf
chapter-11-pointers.pdfstudy material
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxmonicafrancis71118
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfjanakim15
 
C++ and Data Structure.ppt
C++ and Data Structure.pptC++ and Data Structure.ppt
C++ and Data Structure.pptRich Alex
 
C Languages FAQ's
C Languages FAQ'sC Languages FAQ's
C Languages FAQ'sSriram Raj
 
Rpg Pointers And User Space
Rpg Pointers And User SpaceRpg Pointers And User Space
Rpg Pointers And User Spaceramanjosan
 

Similar to Under standing pointers in c 3rd edition (20)

Pointers
PointersPointers
Pointers
 
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
Microcontroladores: Programación en C para microcontroladores con AVR Butterf...
 
Pointer
PointerPointer
Pointer
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
A TUTORIAL ON POINTERS AND ARRAYS IN C
A TUTORIAL ON POINTERS AND ARRAYS IN CA TUTORIAL ON POINTERS AND ARRAYS IN C
A TUTORIAL ON POINTERS AND ARRAYS IN C
 
Arrays and pointers
Arrays and pointersArrays and pointers
Arrays and pointers
 
Pointers
PointersPointers
Pointers
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
chapter-11-pointers.pdf
chapter-11-pointers.pdfchapter-11-pointers.pdf
chapter-11-pointers.pdf
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
 
Pointer
PointerPointer
Pointer
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Pointers In C
Pointers In CPointers In C
Pointers In C
 
Pointers
PointersPointers
Pointers
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdf
 
C++ and Data Structure.ppt
C++ and Data Structure.pptC++ and Data Structure.ppt
C++ and Data Structure.ppt
 
C Languages FAQ's
C Languages FAQ'sC Languages FAQ's
C Languages FAQ's
 
3rd Semester Computer Science and Engineering (ACU - 2021) Question papers
3rd Semester Computer Science and Engineering  (ACU - 2021) Question papers3rd Semester Computer Science and Engineering  (ACU - 2021) Question papers
3rd Semester Computer Science and Engineering (ACU - 2021) Question papers
 
Rpg Pointers And User Space
Rpg Pointers And User SpaceRpg Pointers And User Space
Rpg Pointers And User Space
 

Recently uploaded

Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 

Recently uploaded (20)

Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 

Under standing pointers in c 3rd edition

  • 2. Table of Contents Aclotowledgments 2. Pointers atrd Arrryr ... Jntrcduc|ion Io Second Edhiot IDtroductio[ To Poitrters,,,,,....,..;...............,.......-.......1 The & and , Operctors, 2 Poifier Explessions, 4 The Jargon of Pointers, 9 char, int andfloat Poihters, 9 Passing Addrcsses to Functiohs, 12 Fuictions Retuming Pointers, 15 Solyed Problems, 17 Exercise, 30 Pointers and Stings, 142 The const Qualifier, 143 Retumirrg eonst Yaluef, 146 Two Dirtensional A|ray ofCharacters, 147 Array ofPoirers to Strings, 149 Lirnitario4 ofArray ofPointers to Strings, I 52 Solved Problems, 154 F,xerclse. 184. t tv,'4. PolnterrandStructures ......,..........------------.,.........189 An Array of gructures, 191 Mole about Structures, 192 Structure Poi ters, I94 Offsers ofstructufe Elemehts, 196 Linked Lists, 200 Stacl$ and Queuet, 220 Doubly Lhked Lisk, 2ii Solved Prcblens, 243 Etercise,270 5. Pohters rlrd Dats Structurcs ...,......,.,..........,,,,.....,,,...,....279 Mergirrg dLinked Lists, 280 t- llhat are Arrays, 38 Passing Atay Elernents to a Function. Poihters and Atays, 43 Pqssing a4 E ttirc Affoy to a Function, TheRealThing,5l Morc Thqn One Di ension, 52 Poinlers arrd Tfuo Dimetsional Arrays, Poi tetto sn Atay, 58 Pdssing 2-D Arroy to a Function, 59 Three Dimensiondl Arrays, 62 Passing 3-D Array to a Functiok, 66 Retuming Aftayfrorn Fuictiot , 69 Relumifig 3-D Aftay from a Function, Array of Poi ters, 82 Dyuhtic Memory Allocation, 84 Solved Problems, 87 Erercise, 130 Pointers and Stiitrgs ,.....................133 Wat are Slrings, 1j3 * Li ked Lists and Polynonials, 285 Sotting a Lin*ed List, 297 Circalar Linhed List, 323 Trees, 326 Binary Tre*, j28 41 50 3. Stqhdard Library String Funcrions, I38 vt Traversal d a Binary Tree, 33 1 Deletionlrom a Binary Tree, 336 Threaded Binary Tree, 344 Graphs,356 Solved Problems, i69 Exercise. 389 6. PointersMisceIlrtry..,,,.....................................................391 File Poi rets, 391 Pointers to Functions, 394
  • 3. typedef with Furrction Potuters, 397 srgc and srgv - Arguments to mairt( ), 398 Poin ers afid Ydriable Nurnber of Argunen s' 399 rcor,lat and huge Poinlers, 40i Which Poi en to Use?, 408 Physicol ,4ddrcss to Segne :qsel 4 I I The Darcing Dolls, 412 Caps Locked!, 413 How Much Memory Do You Have?, 415 Exercise,4l7 7. Appllcrdorr of Pohters '..,....--........................................423 Exploting the Dith 423 Dictioiary, 434 Manoging Database, 439 The Keybod Queue, 459 InJix to Postfa, 462 Evaluation of Postfa Exprcssion, 467 Locatw Duplicote Filelanes, 469 Eoshing 474 i Function Calls and Stqck. 480 Solved Probtens, V85 I tnrex | 493 Preface to Third Edition In all walks of life anythiDg can be done better the next lime around. I realised this more emphatically when I completed lhe third edition oftlds book. Ihus, Ore so-cJlled ,perfect' c'hapters of the second edition had to be redone for more clarity and simplicity. For quite some time now I have beeo getting requests fiom readers that the chapter on .pointers and Oata Structures, be made more elaborate and exhaustivg. I have completely overhaule.d this chapter. Now it also includes binary treis ani graphs, While reading the fust draft ofthis edition I felt that something is missin-gin this book. It was only when I was ttuougtr *ittr rtr! final draft I.realisgd that the missing link (poinrer) wa-s a chapter on applications of pointers in real-world programming. After all, no amount of theory is useful unless you cun poi it into practice. So the final draft became semifinai since I decided to add this chapter to the book. And now I am presenting you the edition which I feel is complete in all respects, lili I "-pmying tlat I won't be required to wrire aflother editiol of this book, Any author would testiS/ that writing a new edition is always more palD in the neck than writing a fresh title. tt
  • 4. 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.
  • 5. 2 Understanding Pointers In C Chapter 1: An Introduction to Pointers 3 It is difficult to get a grip on poioters just by listening to programmer's jargon, In our discussion of C pointers, therefore, we will try to avoid this difliculty by explaining them in terms of simple programming concepts. The fi$t thing vi,e want to do is eplain the rationale ofC's pointer notalion. We oan print this address through 1Le /- Program 1 */ main0 { inti=3; following program: The& and * Operators Consider the declamtion, This declaration tells the C oompiler to: (a) Reserve space in memory to hold the integer value. (b) Associate the name i with this memory location. (c) Srore the value I ar this location. We may rcpresent i's looation irl the memory by the following memory map: i-__} El--*6485+ Location Dnme I-ocation no. (Ad&ess) Figure l.l We see that the computer has selected memory Iocation 6485 as the place to store the value 3. This location number 6485 is not a number to be relied upon, because some other time drc computer ult r, may ohoose a different location for storing th€ value 3. impofiant point is, l's address in memory is a number. printf ( "nAddress of i= %u^, prlntf('hvalue of i = %u", i) ) l'he output ofthe above program would be: Addrcss ot i= 6485 Value of i= 3 &i) ; inti=3; l,ook at the fi$t printf( ) statement carefully. The .&, opeBtor [sod in this statement is C's 'address of operator. The expression &i retums the address ofthe vagi4llglwhich in this case happens lo be 6485 pointer operator avaikble in C is '*'. called 'value at erator. It retums the vaiiE stored at a particdlalEddfess. also called an 'indirection'at address' operator is l,hlene carefully the output olthe following programj /' Program 2 '/ nrain0 I inti=3; printf ( "nAddress of i = %u', &i) ; %d-, i) ; %d",.(&i)); printf ( nvalue ofr = other ess o e'value orator. printi ("nvalue of i= ) Ttre
  • 6. IJnderstanding Poinlers In C Chapter I : An Introduction to pointers4 5 The output ofthe above prog€m would be: Addressoli=6485 Valueofi=3 Value oli = 3 Note that pdnting the value of *( &i ) is ofi. As you can see, i,s value is 3 andj,s value is i,s address. "l:1^1"]! ". :an'r use j jn a program wilhout dectaring it. And8rn.e j rs a arjable. which conlains lhe addre., of i, it is-aeilurea-0r. lnl 'j ; 'lltis declaralion tells the compiler that I will be used lo store therddress ofan integer value _ in o*re. *Jro.; poino ,o _ iri"g;;Ilow do wejustify tlie usage of * in the declaiation, lnt'j; 1;d ,t g:-Py the meaning of +. It stands for ,value at address,, I hus,.irt *J would mean, the value at the addre* ""","rn"ji, ij, same as printing the value Pointer Expressions Let us now see what are pointers and how they can be used in various expresJions. We hav9 seen in the previous section that the expression &i retums the address ofi. If we so desire, thig address can be collected in a variable by saying, But rcmembcr that J is not an ordinary variable like any other int€ger variable. lt is a variable, which contains the address of llcre is a program that dcmonshates the relationships we havet ccn discussing. another variable (t in this case) Since J is a variable the compiler must provide it space in mernory' Once again, the following mcmory map would illusts?te the contents of I and J. E'.-l 6485 3276 Figure 1.2 j=&i; I Program 3./ maino ( inl i= 3; int 'j ; j=&i; pdntt ( 'nAddE$ of i = %u', di ) : printf ('nAddEss of i = %u'. i ) : Printf ( 'nAddress ofj = o/ou', ai) ; pdntt("nvalueotj=%d'. i ) :'pdntf ( 'hvatue of i = %d", i i : pdntf ( 'hvalue of j = o/od,. .{ &i ) I . Printf ('nvalueof i = %d' l) "'
  • 7. 6 (Jnderstanding Pointers In C Chapter 1 : An Introdaction to pointers 7 The output ofthc above program would be: AddEssoli=6485 Addressofi=6485 AddEssofl=3276 Value ofl = 6485 Valu6 ofl = 3 Valueoli=3 Valu6 of i= 3 Wo* thrcugh thc above program caretulln taking hclp of the memory locations of t and J shom ea isr. This program summarires everything we have discusscd so far. If you don't understand thc'program's output, or the meoning of ihe oxpregsions &1, &J, rl ard *( &l ), re'read the last few pages. Evcidring wc say about poilters ftom hcr€ onwards will dcpcNd on your understanding ofthcse exprcssions thoroughly. Look at the following dcctarations, lnt'alpha; ohar 'ch ; lloat 's : Hcrc, rlphr, ch and I ale declarcd as pointer variablel, i.c' variableicapable of holding addtesses. RfiIember that, addrgsses (location nos,) ar€ always going to be whole oumbe!$, thorcfore pointers ahvays contain whole numbers. Now we call put these two iacts togethir and say-poiotels are variables that contain since addrcsses ai;;lwaysE;G;mBEiies!way would always co!!Bi! concept of pointer caD be further extended. pointer we know is a vadable, which contairc address of another variaUte, Niw thii variable itself could be another pointer. Thus, we now have a pointer., whicb.contains another pointer.s address. The following example should make this point clear. f Prcgram 4'l maino { iiqt i= 3; int'j: lnt nt; j= &; k=&j; pinf ('bAddr€ssof I = %u., & ) ; Ptinu ( trAddcss oti= oi6u', j ): pdntf ( lnAddEss of i = %u., ik ) : Pdntf ( 'nAddrsss ofj = %u', &j i ; pdnf ( lnAddrEss ofj= %u', k ): prinf ( tAddrBss ofl( = %u', &k ) ; prinf ( lnhvdus ofj = %u', j); pdnf ( Walus of k r %u', k ); printf ( 'nvalue oti = %d', t)j pdntf( lnvaluo ofi =/od',.(&j))j pdnf (hvalue of i = %d", J ); pdnf( lnvalueofi = %d',,* ); The declaration llgat *Ejqes not mean lhat s is going [o cooBln a fl oati-ng-point valqq. @ --aterisi-oIa'hoating-point value. Similarly, char *ch means that ch is going to oontiin the address of a char value. Or irr other words, the value at ad&ess stored in ch is going to be a ch'r' The The output ofthe above program would be: Addressoti=6485 Addre6sori=6485 AddEssofi=6485 AddEssofj=3276'
  • 8. 8 Understanding Pointers In C Address ofj= 3276 Addressolk=7234 Value ofj= 6485 Valueofk=3276 Valueoli=3 Valueofi=3 Value of i= 3 Valu6ofi=3 The following memory tDop would help you ir tmcing out how the prcgram prints dle above outpul. Figurc 1.3 Obs€rvc how the variables l, J and k have been declarcd, inti; lnl -l i int -k i this, one mrely requires to just in case... extend the definition of a Pointer' But H€re, I is an ordinary ldt, I is a pointer to ar lnt, whsreas k is a poiflrer to a pointer. ln pdnciple, there could bG a pointer to a ;ointer to a pointer, or a pointer to a pointer to a pointer to a pointer. There is no limit on how far can we go on extending this a€finition. Possibly, titl the point we can csrFehetrd it' And that point of oomprehensiotr is usually a pointe, to a pointer. Beyotd char, int zad.Jlod, Pointers Considei the followiog program: f P@gran 5'/ main( ) { charc,'cc; int i, 'ii; I 3 J 6485 k 3216 6485 3276 1234 The Jargon of Pointers Consider the following program segment: inta=35; inl 'b : b=&a; Now can you guess which ofthe follo.f,ing statemenis are coneotl (a) b contains address ofan ht. (b) Value at address contained in b is an lnt. (c) b is an ltrl pointer. (d) b points to an t!t. (e) b ig a pointer which points in the dileotion ofan lnt, 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 b contained an address of a flort it would have beoome a flolr pointer. with the same argument if we have three Doiflter variableg first containing addrcss oian array, second contai;ing ad&ess ol,a structure and third containing address of a fuflction then It woulo be appropliate to call these ai an array pointer, a structure poinler and a fiinction pointe! respectively.
  • 9. float a,'aa; c = 'A I ascii value of A gets stored in c t/ i=54; a= 3.14; ii= &i i aar&ai pdntf plintf pdntt p ntf pdntf printf ) And herc is the output, , , Address conhined in cc = 1004 Addr€ss contain€d ln il = 2008 Address c.ntalned in aa = 7006 Vslue ofc = A Valui of i: 54 Valueofa=3.140000 Note that in the prltrtf( )s the addresses of chrr, lnt ard lhe no't all have been prioted using the fomat specifier 7ou, Sometimes the address miy tum out to be a number smaller than 32767. ln such a case we may use the fomat specifier 7"d to pritrt the address. Also observe that though the integer va able i occupies two brtes in mernory the stalement ii = &l stores only the addEss ofthe first blte, 2008 itr il (refer Figurc 1.4). Similarly, " = &a stores only the address of the flrst byte (7006) out'of forE bytes occupied by the float variable a. Chapter 1: An Introductia to Pointers t1 Figue 1.4 Thc address of first byte is ofton known as thc base addrcss. Though ll and rt contain ody the base addrcsses, the e*ftdssions *ll and *aa allow access !o all the bytes occupied by the intcger I and a rcspectively. This is because il and a& haye been dcclarcd as itrt and llort pointers respectively. Since il is an itrt pointer, *ll must fetch ar lrt. Similally, since aa is a flort pointer *ar must fetch a lloat. Do you &ink the following program would work? And if it does what would be its puttr ui? Address contained in cc = %u", cc ) i 'nAddr€ss conbined in ii = %u", ii ) ; 'nAddl8ss ontained in aa = %u', aa ) i "ivalue of c = %c', 'cc ) ; lnvalue of i = %d', 'ii ) ; 'Vrvaluo of a = o/ol, "aa ) ; f ftogram 6'/ main( ) { inli=54; float a = 3.,l4; char'ii, 'aa ; ii= ( char . )&i; 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', ) : EI1004 lE;;l:;7l 2009 ii m8l 7602 7006 7007 7008 7009 @1962 3.14 ,13
  • 10. 12 Understanding Pointers In C Chapter l: An Introduction to Pointers 13 p ntf ( "hvalue at lhe addrcss contained in aa = %d', 'aa ) ; ) Note that here ll and aa have been declared as chsr poioters. Still rhe statemenrs ll = &i and ra = &a worElqnce again tbe ad&esses 2008 and 700d (refer Figure 1.4) get stored in ll and m which are printed through the first two prtntf( )'s. However, the prcgram 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 one contained in 7006, 7007, 7008 and 7009. Moral is, ifyou vdsh to acoess an integer value stored in a variable using its addr€6s, it's rccessary that the ad&€ss be stoEd in an 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 a float pointer. Passing .dddresses to Functions Aryu.ments arc generally passcd to fulctions in one of the two waysr G) Bending the values of the arguments sending the addresses ofthe arguments(b) In the first method the 'value' of each 4crzal atgumetf in the calling functiol is oopied into aonespondirg forr al argumcnt of the called function. With this method, ohanges rnade to tlre fotmal argume[ts irr the called function have no effect oo the values ofthe sqtual argum€nts in the calling function. following Eogram illustrates the 'Call by value' r p.J,l,ff z r ( inta=10i irt b = 20; swapv(a,b); pdntf(tla=%d",a); printf('bb=%d',b); ) swapv ( int x, inl y ) { pdntf(u=%d",x)i Printf (y = %d", y )' ) The output ofthe above program will be: x=20 v= 10 a=10 b=20 inlt; t=x; x=y; y=t; Note that values of s and b remain unchanged even after exchanging the values of x and y. In the secold method (call by reference) the addresses of actual arguments in the calling futlction are copied into fonnal arguments ofthe called function. This means that using the fomal argumeflts in the called funotion, we can make changes in thJ actual arguments of the calling function. The following program illushates this fact.
  • 11. 14 Understanding Pointers In C Chapter 1: An Introduclion to Pointers 15 areaperi (radius, &area, &perimeter ) i printf ( 'Area = %f, area ) ; printf ( 'nPerimeter = %f', pedmeier)j areapei ( int r, ioat 'a, float *p ) 'a = 3.14'r'r; 'p = 2'*3.14' r; And here is the output... Enter radius of a circle 5 Area = 78.500000 Perimeter = 31.400000 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 chaflge effective even in main( ). That is why when the conhol retums fiom the function areaperi( ) we are able to ourpul the valuos ofiare! and perimeter. Thus, we have been able to rctum firnction. This helps us to overcome f Progtam 8 ./ main( ) { inta= intb= swapr (&a, &b ) ; pdntf ( "na = o/od" printf('nb=%d" i swapr ( int *x, int -y ) { inlt; t=-li ) 10; 20l ,a); ,b); The output ofthe above program would be: a=20 b=10 retum more than one value at a time, _which is not possible ordinarily. This is shown in the program given below. lime statement, which can rctum only one value ftom a function at a Using 'call by reference' intelligently we can make a function /. Program 9'/ main( ) { int radius i float area, perimeter j printf("nEnter radius ofa circle " )j scanf ("%d", &radius ) ; Functions Returning Pointers The way functions retum an int. a float. a double or any other.lala tlpe, it can even retum a pointer. Howevei, to make a funcrion retum a pointer it has to be explicitly mentioned in the calling function as well as in th€ function definition. The following program illustrates this. two valuos from a called the limitation of the return
  • 12. 16 Understanding Pointers In C Chapler L An Introdu( tiott to Pointers 17 /* Program main0 { u",p); d",-p); int'p; int -fun0 ; P=fun0; printf ( 'n% printf ( "n% 10-t /" prototype declaration */ *iun( ) /- function defnilion */ inti=20; relurn(&i); Solved Problems lAl What will be the output oflhc following programs: (1) main0 t int i= -5, j= -2; junk (i, &j); printf ( 'ni = %d j= %d", i,l junk ( int i, int tj ) ( l- I li ) ); int t ) This progmm shows how a pointer can be rctumed from a funotion. Note that the prototlpe declaration tetls the compiler that fun( ) is a function which receives nothing but returns an integer pointer. The first prlntf( ) would output the address contained in p (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 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 shown below: static int i = 20 ; -5j variable names in differcnt functions? Yes, by all means, without absolutely any conflict. Thus, the two sets of i and J 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( ), Jutrk( ) gets reflected back in maitr( ). Hence evaluates to 4 is reflected back in main( ). any -J- change in *j, which Output Explanation One doubt immediately oom€q to the mind----can we use same
  • 13. 18 Understanding Pointers In C (2) #include "stdio.h' main( ) { int a, b =5; a=b+NULL; printf('%d',a); ) Output 5 Explanatioa NULL has beea defined in ',stdio.h,' as follows: #define NULL 0 Heroe, duiing peprocessiog NUff *,in be rrplaced resulting into 5 getting stored irr r. (3) #include 'stdio.h' maioo ( - printf ( '%d %d', sizeof ( NULI- ), !*zeof(.. ) ) ; ) Output 21 Explanotiot Chapler 1: An Introiluction to Pahtters 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. Even though the string -' is empty it still contains the character, '0'. Hence its size arrrrs out to be I bvte, (4) main0 { floata=7.999999; float'b,'c; b=&al c=b; printf ( tu%u %u %u', &a, b, c ) ; . printf (tl%d %d 96d 96d., a.( Aa ),.b,'c ); I Output 4200 42N4N0 0 24576.318115 Explaaatioa 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 prtntf( ) prirfs the address of a in three differcnt ways. No problem therc. What is supdsing is the output of the second printf( ). Through this pritrtf( ) we are attempting to print 7.999999 by. applying pohler operalors on a, b and c. a, *(&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. 19 bv o,
  • 14. 20 Understanding Pointers In C So always remember to use 9/"f to print floating point values. Don't rely on printf( ) to truncate a float value to an integer du ng pinting by using a yod. Vice versa also it is t[ue. The following statements wouid not print 7.000000. Don't be suryrised ifyou get some odd value. In that sense y"d and ohf are a Iittle unreliable. inti=7; printf("%f',i): (s) mainO ( , int.c; c=check(10,20); printf("hc=%u',c); ) check ( int i, intj) ( int.p, rq ; p=&i; q=&j; if(i>=45) retum (p ); else retum (q ) ; ) Output Enor message: Non ponaue pointer assignment in main E)tpltiafion The rcason for the eror is simple. The integers being passed to check( ) arc collected in i and j, and then their addresses Chapter l: An Introduction to pointers 2l are assigred to p aDd q. The[ in the next statement the conditional operato$ test the value of i against 4j, anJ ;;tu;either the adtlress stored in p or the adjress ,t""J iil. f"t appeaE that this address would be collected in c in maijt t 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 intefer. Thus j"ust declaring c as an iDteger pointer is qot sufficient. We must make the following modificaaioru in the progmm to make it work properly. main0 ( int 'c j inl 'check ( in! int ) ; c = check (10, m ); pdntf(tuc=%u.,c); ) int 'che6k ( int i, int j ) ) (6) main( ) t tloat.jamboee ( fod.); float P = 23.5, 'O , q=&p; pdntf ( tlq bebre cdt = 96u', q ) ; q=jamborBe(&p); printf ( q afler ca[ = %u., q ) ; tloal 'jamboree ( foat t ) t=t+1:
  • 15. Unders tatding Point ers W Chapter l: An Innoduction to pointers 23 rBtum ( r) ; ) OutPut q bebtB call = silg8 q aier call = 5502 Explatation ' [Bl ANwer tb€ folowing: Explatatioa ( tpb )++ ln mrtd ). q has be€a d€clarEd as a trott pointer' lt means q ;; ;-G;il capable of holding the addtess of a flori rrt-rnf, o = Cr'm "aat""" of p' a ltoal is stored ia q and ,fr*,i"fu "ri,t-"gl th" p"iotf( ) This is the value of q il.i.,{'i"i-urt-*t li"Erle<I.'whetr-irmboree( ) i8 called the ffi;:Jir;i" "X; i, -a i" *u""t.a i" '' At this^juncture r contains 5498 lwhen $'e ratr the progmm it was 54vui wnen ,a" "*a"a" *" paga- this may tum our to be somc olher lia*""1. Wr,* t i.ircremented it would become 5502 whv .-"t* #+i S*""* . is a tro.t pointer aDd on incrmentiflg il i"'iii*.rfa poin r. {re nert ll'oat which would be F€sent 4 iL*. rt"oo. il*. cvery Oo.t is 4 bytes lotrg The return "tat"rnent tl"o rett^" lhis adrlress 5502 back to EalD( Since a llo.t poiott is bsitrg retume4 a deElaration-.lloat *lembore. ( flort') is necessary in main( ), whrch tolls me 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 a llort poirtcl. (2) !r th€ followinS gogrm add a stat€.ri€ot in the fi[roiion fu( ) such tllat ad&ess oft gels stored h l. L main0 { int'jl roidtun(i -); tun(&j); ) void tun ( int -k ) t inl a ='10; I add staEment he,E *,/ ) Explatation 'k=&a; the pofut€r and oot the value pointed iacrements tle value befug pointed to ( I ) Can you write anoth€r exEessioo which does the same Job as .-1'pE9 9) Are the expEssiotrs ipff+ aod #rph saDe? Explanation No. *Ptr+ inorcments by it, whereas, +rph by ptr. (4) Where can poit*€rs ie used? Explarration
  • 16. {Jnderstanding Pointers In C Chapler l: An lntroductian to Pointers 25 At lot ofplaoes, some ofwhich are: - Accesshg array or s&ing elements - Dynamic memorY allocation - Call by refereace - Implemeding lioked lists, tre€s, $aPhs and many other data structures Eiplanation No. An efior would be .eported i[ the statement k+arithmetic on void pointeE is Dot permitted unless the slnce void (5) Would the following waming? <Yes/No> main0 ( ioat i = 10,1; bid'k; k=&i; j= k; pdntl(ln%f,l); ) Erylaaation Eogram grYe a comPilatioo enor or pointer is appropdately typ€casted. (7) Would the following prograrn compilatioo? #include 'stdio-h' main0 ( int'p1, i= 25; void .p2 ; p1 =&; p2=&i; p1 = p2: p2=p1; ) Expla ariqn No (8) Would the following program compilatioa? . #include 'stdio.h' main0 { float -p'1, i= 25.50; chat *p2,, pl=&i; p2=&i; ) Explaaatiott give any wamiug on give atry waming on No. Here no tipecastirg is required while assiguing thc value t -*Jto. I L""ugrao*lsioq" ,"t" uopl&d-gU@or'"ntlv *teo ooo po-i"tertypes are assigned to atrd fiom vold '' (6) Would thc followiag Pmgr& contpile? main( ) { int a = 10,1; sid'k; i=k=&a; j++ ; k+; printf ( lyou %u', i, k ) :
  • 17. Unders landinE Pointers In Chapter 1: An Introduction to Pointers 27 ( Yes. The wamfug wonld be "Suspicious pointer conversion itr firnction maitr( )". 9) What is a oull point€d Explanation For each pointer typ€ 0ike say a char pointer) C defines a speoial pointer value that is guara eed trot to point to any object oi fiuctiotr of that type. Usually, the null pointer consta used for rcprcse itrg a dull pointer is the integer 0. Ud WUf" fi" Aff"r.o"" between a null pointer. a NULL macro. - the ASCII NUL character and trullstring? Explanatiot A null pointer is a pointer, which doesd't point a[ywherc' A NULL nla ro is us€d to represeot the trull pointet in source code. It has . value 0 associat€d wilh it. l The ASCtr NUL character has all its bits as 0 but doesn't have any relationship with lhe null pofuter. The trull string isjusr atrolher oame for aD empty string "". (l l) In which header file is the NULL rnacro defined. Explanotioa , In files "stdio.h" and "stddef.h". (12)Is the NULL poirti:r same as <Ye$No> Explakation No an uoitritialised pointer? Ellvironltre set two of,tlE data segnent and (13) above for details). (l3)What does the error ..I{ull pointer Assignment, mean and what causes this e.rofl Explanation The Null pointer Assignment eEor is generated only ia small ard medium memory models. This error occurs in programs, which attempt to cbange the bottom ofthe data ,"gJ;t..-----' 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;iBodand Intl.". In the small and medium -".ot;;"i;;;null pohter points to DS:0000. Thus assignhg u ;ulu; ;;;memory refer_enced by this pofuter wilt ov;rwri-t" tte nrsi ."ioD,,le In fie data segnent. At progmtD terEination, the four zercs and rhe copydght bamer arE ch€cked. Ifeithei has been mo.di fie4 then rhe Null poiDter Assigftretrt error is generated. Note that the oointer may not truly be Du[, bur maibe a wild polnter that rcferences these key arcas in the data sigrnent. ( I4 ) How do we d€bug a Null poifter Assignment erlor? Explanation In the lrtegrated Development watohes- -olre pohting to the bottoE another pointing to the banne. (refer
  • 18. 1e Undennnding Pointen In C These wat hes, ed what they should display in the watch window, are: '(char J4,42MS 'Borland C+r - Copydght 19gl Bodand lntl., (ch ')0 NU|I Of course, the copyright bamer shown above will vary depending otr your ve$iotr ofthe Borland CyC+ compiler. You can t)?e the following program and step through your progam using F8 or F7 and modtor ihese values in thi witch window. At the point wheir one of thern chaages, you have just executed a statemerf that uses a pointer thai has-not been prope y initialized. #inclds 'dos.hi #include 'stdio.h' #nclude 'stirE.h' main( ) ( char 'ptr, 'banner ; pr: ( char') MK_FP (_DS, 0 ) : banner = ( char' ) MK_FP ( _DS, 4 ) ; sfEpy ( pt, rhi' ) ; s[cpy ( banner, 'hello') ; pdttf ( lncood iloming' ) ; ) Nole that a Null poiDter Assigtrmetrt ermr is trot generaled in all models. Il the compact, hrge atrd huge memory models, frr pointgrs are us€d for data (Refq C-nupte" O fo, -o."mfonytion about m€mory models and far pointers). Therefore, a null poiater will reference 0000:0000, oi tle tase ofsystem memory, atrd using it will trot cause a comrption of Chapter l: An Introduction to pointers 29 the key values at the base of tbe data segment. Modifuing the base ol systern memory usually causes a system crash, however. Allhough it would be possible that a vrild pointer would overwrite the key values, it would Dot indicale a null pojnter. It the tiny memory model, DS = CS = SS. fterefore, using a null pohter will overwrite tb€ beginning of the code segment. ( I 5) Can anlthing else generate a Null pofuter Assignoent error? Expla atiot Yes. using a wild pointer that hsppeDs to reference lhe base area of the data segment may cause the same error since this would change lhe zeros or the copyright bauner Since data corruption oa staok comrption could cause an otherwise-valid poi[ter to be corupted and point to the base of the data segment, emy memory corruptioD could resull in this 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 lnitr:lize4 elac€ a- watgh on lat poirter- Srep througn your Fogram again and watch for its value laddressj to chaige, ICI What do the following declarations stand for? int *i ; ,loat -i ; char*k; voidf(int',chart); floattg(floatt,ioal-); int*h(foat',char-); b.plahatiot
  • 19. 30 Understanding Poinars In C I is a pointer to a pointer to a pointer to an itrt. j is a pointer to a pointer to a lloat. k is a pointer to a pointer to a pointer to a pohter to a char. f is a function which receives an itrt pointer alld a char pointer and rctuIus trothing. g is a function whicb receives a float pointer and a poinler to a float pointer and in fum rehrms a float pointer. h is a function which receives a flort pointer and a pointer to a char pointer and in tum rcfums a pointer to an itrt pointer. Chapter I: An I trod ction to Pointers 31 Exercise (2) mdno { shar c, 'cc ;' inti; long I ; ioal t; i='15; I = 77'177 i f= 3.14 ; cc = &c; pdntf ( trc = %c cc = %u', 'cc, cc ) ; cc=&; pdntl('bi= gtd cc = %d, *cc, cc ) ; cc = &l; printf (1nl= %ld cc = %u', 'cc, cc ) ; cc=&l; pdntf ( 1nt = %f cc = %u', 'cc, cc ) ; ) (3) maino { intcr10,d=m; pdntf pdntf pdntf swap printf pdntf IA (1) I Wtat $r'il1 be lhe output ofthe following programs: maino { int a, 'b, *c, *d, *e ; a=10; b=&a; c=&b; d=&c; e=&d; pnntf ( 1na = %d b = %u c = %u d = %u e = you', a, b, c, d, e ) ; pintf ( 1n%d 96d i{d', a, a + rb, *c + Ed + tre ) ; ) We ale in main( )....') ; lnAddtess orc= %u Address ofd = %u", &c, 8d ) ; lnBebre srflBp( ). c=Yod d=%d',c,d); c,d); !Bek b main0....'): Afldr swaD( ), c=%d d=Yod',c,d); ) swap (intc, inld ) { pdntf ( lnwe ale in ${ad )....' ) ; printl ( lnAddless ofc = %u Adrcss old = %u', &c,8d )j pdntl (1nBetore chang€{ ), c = 96d d=yod',c,d);
  • 20. 32 (lnderstan"ding Pointers In C change(c,d); printl ( "hBack to $rap( )....' ) ; pdntf ( "nAfier change( ), c=%d d=%d',c,d); I change (int q intd ) { intt; 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 ) ; t=ci c=d; d=t; b ntf (After interchanging, c=yod d=o/d',c,d); ) . i4) main() ( intc='10,d=20j printf ( "nBeforc s!,/ap, c = %d d = 7od', c, d ) ; swap ( &c, &d ); printf ( Affer suEp, c=96d d=96d',c,d); ) swap ( int 'cc, int *dd ) { exchange ( &cc, dd ); ) exchange ( int *cq int *dd ) { intt; ,_cc = .dd ; Chapter 1: An Introduction to Pointers 33 'dd = t; ) (5) maino t inta=5,'aa; aa=&a; a=power(&aa); printf{'ba = Yod aa=%t,a,aa); ) power ( int *ptr ) { intbi b = *pt'*fitr ; retum ( b ); ) (6) maino { inti=3; foat I = 3.50, 'plod ; float' multiply ( irt float ) ; pmd=multiply(i,f ); A printf ( lnplod = %u value at addess = 7ol, pn2d, 'prod ) ; t ) ioat ' multiply ( int ii, flo6t ff) t float producl ; product=ii'fi; pdntf ( lnprcduct = %l address of prcduct = o/ou", product, &product) ;
  • 21. rctum (&product); main( ) { char'c = 4000 ; inl 'i = 4000 : long .l = 4000 ; float 'f =,1000 ; double 'd = 4000 ; printf ( E=%u, c+ 1 = %u', c,c +'l ) pnntf ( 1ni = %u, i + 1 =%u', i i+'l ) ; pnntf ( trl= %u, l+ 1 = 9tu', l, l+ 1 ); printf ( f = %u, q-+'l =%u', t f + I ) : printf ( d = %u, d + 1 = %u', d, d + 1 ) ) maino { int i= 10, j = 20, difl; . diff= &j- Ai: pdntf("haddEssofi=%u atffIess oli = %rf, &i, Ej); pdntf ( 'hdtfeGnce ol addrEsses of i and j is %d'r'diff )i ) main0 { int'i,'jj j=i'2; Pdntf(1nj=o/6u',i) ' ) (10) main0 ( int i= 10: pdnf (1llvalueoli=%d add€ss ofi = %u', i, &i) ; Chapt* l: An Introduction to Pointers 35 &i= 7200 ; printf ( lnneu ydue ofi = 96d neflddless of i= %u", i, &i): ) (11) floata = 3.14; float *z ; foal *y j float *x; foal *v: float *u, ; float * tun1 ( ioat ') ; tloat* tun2 (float-); main( ) ( clrsc( ); z=tun1(&a)l pnnfr ('VNiA? ,a*zl i ) ;oat*fun1(foatt) ( Y=82; v=fun2(&y); retum (*Y ) ; ) float -* tun2 ( float "x ) { w=&x; retum (w); ) lDl Strte True or False: ) 4)
  • 22. (l) Multiplication of a pointer and an uDsigred integer is allowed- { 2 ) Address of a float cao be assigned to a chlr poiioter. (3) A float pointer alwa]rs cotrtaitrs a whole rumber. (4) A pointer p contaitrs addre$s ofa pointer to a'pointer to an iirteger pohte.. To reach the integer value we should use No matter how much time rox hove q)ent with pointers you y,/auld always l d so,rre application oft that woutd leave yoi guessing. Sointm antflrays f he C language providas a capability callecl array that enables I the user to design a s€t of similar data types. Array is a very ^ popular data type with C progrmrnoers. Tbis is because of lhe 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.
  • 23. Understanding Pointers In C What are Arrays An Array is a colleotioa of similar elements stor€d in adjacent mernory locatiom. An odirary variable is o@able of storing only one value at a time. Howwer, lterc arc situations in which we 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 by 100 studerlts in m€mory. In such a case we have two options to storc these marks in me.morl4 (a) Constsuct 100 vadabl€s to storE perceDtage marks obtaircd by 100 ditrcrent studetrts; i.e. each variable cootaining one shrdent's marks. (b) CoNtruct one v{iable (called a subscript€d va able) capable of storing or holding all tlre hun&€d mad(s. Obviously, the s€coDd alkmative is bett€r. A simple reason for this is, it would.b€ rnrch easier to hodle orc %dable tharl haodliag 100 difiem,rt ya.iables. Motsov€r, there arc cartai['logios that camot be dealt wilh, witrcut fr€ usc ofa subsctipted variable. Now a fomBl defiritioa of subccripfed variableg: A subscripted variabte is a collcstivc ame give,n to a 8!oup of 'similal quantities'. Thrs€ similt quantities oould be percentage marks of 100 studcnts, q salcies of 300 €tqloyccq or ages qf 50 snploycrs. Whst iB iryormt is |iat the quaatitiq must be 'gimilar'. Each menrber ia lhe group is reftrred to by ite position in the goup. For ereplc, assu@ the following group of nultlbels thrt repr€s€Et p€rs,coiagc oarts obtaircd by five stuilents. pEr = { 48, 88, 34, 23, 90 } If we w.nt to rEfer to ltG s€codd ntElbcr of the group, the usual nolation used is per2. SiEilady, the foudh rumb€t ofthe group is refsrrEd as perr. Howwer, io C, the fourh nmber is refsrred as pcrl3l. Not€ thal, itr C couttirgofeleme s begirs with 0, and mt L Tlrus. in this example perl3l rEfers to 23 and perl4l rcfers to 96, rn general, the notatjotr would be perJil, where, I cao take a value 0.^1, 2. 3,-or 4, depe[ding on the positiotr ofthe elemenr b€iDg rel'erred. Here per is rhe subscripted variable, whereas, I is it! subscript. A subscripted valiable is also calle.d atr .aEay'. Thus, an a[ay is a collection of similar elemsots. These similar el€m"ot" "orfJ 6" ufi Itrts, or all ,lorts, or all chrE, etc. Usually, the array of chrrs is called a 'striag', wherras an aray ofitts o; tro.ts i" iaffea "implyan array. Remembcr that all el€rne s of any givea array musibe of the same tlTe i.e. w€ camot have e adat of l0 mmbers, of which 5 are ltrts and 5 arp floats, To begin with, like other variables m anay oeeds !o be declarcd, so thd the cotrpiler will kaow wtat tind oim *ray -a m* iargJ an afay we waat For exaEpla, lnt ma*s[30] ; Hcre, lnt specifies the Orpe of thc v{iablg just ss it do€s wirh ordinary ya ables and thr word lnlrltl i! fhe trane ofthe vadable. The aumb€t 30 tells how ooy elcorfias of th€ t p€ ht wil be;our array, This number is ofteo howu as .dimeogioa' of the array. Thc bractct ( [ ] ) trfh lhe coq,il€r that wc are <tealiag with m To fix oul id€as, let us note &*,r a few facb 8boitt ar.ys: (r) Aa anay is a collectio! ofsiDila. elcmerb. It is also knowr as a subscripted variable. (b) Before using an array its tpc ad size trust be d€clarcd. For cxanple, 38 lnt arI3ol ; M TIOOI ;
  • 24. char ch[25] ; (c) The ftlt elemsot io the aray is numbered element is I less lhatr the siz€ ofthe aray. Chapler 2: Pointers and -Arralt: r'l num[] = i ' ) So do rem€rEber tha! ensudog that we do not rcach beyond the array size is entirely the Eograxnmer's botheratioo and not the compiler's. Passing Array Elements to a tr'unetion Army elements can be passed to a furctiotr by callitrg the furction: (a) by value, i.e. by passitrg values of array elements to the function (b) by refercnc€, i.e_ by passiag addre*ses ofaray elements to the function. Programs showing how these calls atE made are given below. l' Pto$am 12'l f Demonstralion ol call by value ./ main0 ( intii int ma s[] = ( 55, 6t 75, 56, 7S, 78, 90 ]; for(i=0;i<=6;{+}) display(mdksll); l/ dlsplay ( int m) ( printf ('h%d', m); l And here's tbe output... 0, so the last (d) 1e) If we so itesiro an aiTay catr be itritialised at lhe same place where it is declared. For exarple, int num[6] = { 2, 4, '12, 5, 45, 5 } i int n = ( 2, 4, 12, 5, 45, 5 ) i ioat pressl] = { 12.3,342, -8.4, -11.3 }: (fl Ifthe anay is itritialis€d wherc it is defind mentioning the dimension of array is optiooal as in second oraqle above' (g) If the army elemetrts a€ not givetr atry specific valucs, they are supposed to cotrtaitr ga6age values (h) In C therc is tro check to s€e ifthe subscript used for an array exceeds the size of the dray. Dat e'ntered with a Eubscript exceeding the array size will simply be plaoed in memory ousiite tie anaft probably oa top of orher data dl ofl the program itsetf. 'ifris witt load to uprcdiotable results, to 6ay iheicast, anrt there will be no error messag€ to wam you that vou are goilg beyond thc array size"In some cases the iomputer rnay just harg. Thus, th€ following progam may tum oul to b€ suicidal: f ProgEm '11 '/ main( ) { int num[40], i; for(i=0:i<=100;i+|) 66 06 76
  • 25. 42 Understatding Pointers In C Here, w€ arB passing ao individual aray el€inent at a time to the tunctiotr dtsplay( ) aod getting it pdnted in the tunctior dtiplay( ). Note that since at a time ody otre elemeot is being passed, in the functiotr it is collected in a odirary integer variable m. And mw the call by referenc.e. f Prcgrarn 13'/ f Demonstralion ofcall by lefelence'/ main( ) ( inti; ini ma s[] = { 55, 65, 75, 56, 78, 78, S0 } : for(i=0;i<=6;i+) disp (&m*s[ ]; ) disp ( int 'n ) t pdntf ( "Vr.rfi', 'n ) ; ) Atrd h€re's the output... Chapter 2: Pointen and Arays 43 Here, we are passitrg addrcsses of individual array elements to the functioo displsy( ). Herce, the variable in rphioi this addrcss is collected (n) must be a pohter variable. And sitrce n contains the address of array elemetrt, to pdtrt out the arrly element we must use the 'value at address' operator (*). Read the following p.ogram carefrlly. The pu4rose of the firnction is to just display the arlay elernents on ihe icreea. The program is only patly complete- you are required to *dte thi iraction show( ) on yow olvtr. Try your hand at it. /. Program 14 ./ main0 { int ij int ma*sll = { 55, 65, 75, 56, 78, 78, 90 } ; for{i=0li<=6;i++) disp ( &marks[] ) ; ) disp (int.n) { show (An ); ) Pointers and Arrays To be_ able to see what pointers have got. to do with arrays, Iet us first leam some pointer aritlmrctic. Consider the foiowing example: f ProgEm 15 */ main0 { int i = 3,'x; floa1= 1.5, 1' char k = 'c,, *z ; 56 78 78 90 55 65 75 56 78 78 90
  • 26. pdntf('Vtvalue oli= 96d", i); pdntf (Walue ol j= %f, j); pdntf (Walue of k = 9dc', k); x=&i; y=&j; z=8*; pdntf ( tnoiginal value in x = %u', x ) ; prinf ( 1nodginal value in Y = %u'' Y ) ; pdntf ( 'hodginalvatue in z=%tt,zli pdntf ( lnvrNew value in x = %d, x ) : printf ( 'hNew value in Y = %u', Y); pdntf ( tNew value in z = %u', z ) ; ) Suppose l, J and k are storcd itr mernory at ad&esses 1002, and 5006, the output *,ould be... Value ofi= 3 Value ofj= 1.500000 Valueolk=c Original value in x = 1002 Original value in y = 2004 Original value in z = 5006 New value in x = 1004 New value in y = 2008 New valu8 in z = 5007 Chapt* 2: Pointers and Arrays 45 Observe the last three lines ofthe output. 1004 is equal to original value in x plus 2, 2008 is equal to origitr l value in y plus 4, and 5007 is equal to original value in z plus I . This so happens because 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 incremented, it points to an addrcss two locatioos after the currgflt location, since an int is always 2 b)rtes long. Sirnilarly, y points to an address 4 locatiols after the cunent locatioa and z points I looation after the cur€nt location. This is a very important result and can be effectively used while passing ths etrtire array to a function. The way a pointer can be hcremetrte4 it can be deqemented as woll, to point to ea.lier locations. Thus, the following operations can be perfomed or a pointer: (r) Addition ofa number to a pointer. For exarrple, inti=4,'j,'k; j=&i; j=i't: j=j*9; l=j+3; Subtraction ofa number Aom a pofuter. For example, lnti=4,ti,'k; x++; y++ ; 2004 (b) .8i ; =i-5; k=j-6; word of caution! Do not atterEpt Ore fullorrilg operations lnicrs,.. 0ley would nev€r wort out Addition of two 1,oioters Multiplying a pointer with a numb€r Dividing a pofurter with a atutrbcr
  • 27. Now we will try to corelate the following two facts. which we have already leamt: (a) Array elements arc always stor€d itr contiguous memory locations. (b) A pointer wben incremented alwalrs poitrts to an immediatelv next location ofits qpe Suppose we have an afmy, int numl]= { 23, 34, '12, ,14, 56, 17 }; The following figure shows how this array is located in memory. Chapter 2: Pointers and Anayq 4Z pintf ('addrcss= %u', &numll) ; i*j ) ] The output ofthis program would be: element no.0 address =,1001 element no. 1 addrcss = 4003 element no.2 addEss =,{005 elemenl no.3 addBss = 4007 element no.4 address = 4009 element no.5 addEss = 40'11 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 would be 2 b)'tes greater than its immediate Eedecess;r. Our next two pograms show two ways in which we can access the elements ofthis array. The fitst on€ uses the subscript notation. f Pto$anj7 'l main0 ( inl numl] = { 24, 3d, 12,44,56, 17 }; inti=0i while (i <= 5) ( printf ( 'naddrcss = %u ', &numfl ) ; prjntf ( tlement = %d', numlil ) ; l++ ; ) Figure 2.1 Herc is a program that prints out the memory locations in which the elemenls ofthis aray arc stored. f Program 16'/ main( ) t int nunll = 124,U, 12, 44,56, 17 | i inti=0; while (i<= 5) { printf ( elementno. 96d ., i ) ; 23 34 t2 44 56 t7 400 4003 ,1005 4007 4009 4011
  • 28. 48 Understanding Point*s In C The output ofthis prcgram wottld be: address = 4001 element = 24 address = 4003 element = 34 address = 4005 element = '12 address = 4007 element = 44 address = 4009 demem = 56 address = 4011 elemenl = '17 The next method accesses the array elemeDts using poioten /'Program 18'i main( ) { int ntim[] = {24,34, 12,44,56, 17 }; inti=0,-j; j = &numl0l ; f 6lign address o, zelofi elemenr *l while(i<=5) { printf ( 'haddrcss = %u ' , &numll ) ; pdntf ( "element= 96d', I ) : i++ ; j++ ; f increment poinler b point lo ne* Iocalion '/ ) l The output ofthe program would look like this: address = 4001 element = 24 address = 4003 element = 34 address = 4005 element = 12 address = 4007 element = 44 addrcss = 4009 element = 56 address = 4011 element = 17 Chapter 2: Pointers and Atays 49 In this piogram, to begin with we have colleoted the base address of the array (address of 0s element) in the va.iable j using the statement, j= &numlol; f assigns addr€ss,Oo1 b j'l When we arc inside the loop for the first time j contains the address 4001, and the value at tlds addrcss is 24. These are printed using the statements, pdntf ( address = %u ' , &numfl ) ; pdntf ( "element = %d',I ); On inqementing j it points to the next mernory location of its O?e, that is location ao. 4003. But location number 4003 contains ihe seoond element of the array, therefore when the prltrtf( ) statements arc executed for the second time they pdnt out the second element ofthe array and its addE$s (i.e. 34 and 4003). This oontinues till the last element ofthe array has been p nted. Obviously, a questioa arises as to which oflhe above two methods rhould be used when? Acce$sing a.I:ray elemeds using poi r!!!yq faClgl th!4 qno€ssftg lhein ljr subscripts. However, ftom- lhc point of view of convenience inligramming we should observe the following: Anay elements sholld qe accessed using pointers, if the elements t!!.19-!Eg!!!!99r4 a fixed order, sav &om be EiniGind. or Cof end to besinnliE, or=-ry d temenr rldfinite logic. r lt would be easier to access the elementjfgilgj lubrDriptjfltrEre ,b@"u." llrc, accessing the elements by pointeN would work faster than r atr ltsc ripts.
  • 29. Undersnnding Pointers In C Passing an Entire Array to a F unction Earlier we saw two programs one m which we passed individual elemeds of an array to a firnctio4 and another io which we passed addresses ofindividual €lernents to a funotion. Let us now see how to pass the entile aray to the function rather tha[ individual element.s. Consider the following exarple: f Program 19'/ main0 t int num[] = {24,3'1, 12,,14,56,17}; display(&numlol,6); display ( int'j, int n ) { inti=1; while(i<=n) ( Pdntf ('VElemenl = 9dd', l ) ; i++; j++ ; f increment poinbr b pointb next localion ? ) ) Here, the dlsphy( ) frmctioa is us€.d to print out the array elemeffs. Note that addre$s of the zcmth elsn€ is bciag passed to the dlsplry( ) fitnction. The while loop is same as th€ oDe uled in the eadier prograri to access lhe array elernents using pointers. Thus, just passing.lhe address ofthe zeroth elemeDt ofthe array to a furction is as good as passiry tbe entire aray to lhe firnctionr It is also necessary to pass the total number ofelements io the array, otherwise lhe dtuphy( ) fi.mctioo would not know when to termjrEt€ tte vhlle loop. Note that $e addrcss of the zercth element (often klown as the base addrcss) can also be passed by just passing the name of the anay. Thus, the following two function calls are same: 0qisplay(8num[0],6]; /isplay(num,6); The Real Thing 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 thought. Once again coNider the followi[g aray. 4001 4003 ,1005 AOM 4009 4011 50 Figre 2.2 This is how we would declarE the above atray in C, inl numll={23,34, 12,44,56, ,t7}; We alread_y, know tbat oa meotionilg the name of the array we get its base address. Thus5 by sayhg raum we would be able to r*er to the zercth clement of the arfif,-ilralTfZf GeraD-Easi[sEe that *truE a+L1fl![.+ql!q!Lr€Gr !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, num[il, the C compiler iatcrDally cotrv€{ts it to *( num + I ). This mealts th.t all the followin€ ootatiotrs at€ !ame: numliJ '( num + i)
  • 30. 52 (lndersnnding Pointers In C Chapter 2: pointers and Arrays 53 l1 -ii+num) ilnuml And here is a prcgram to prove my poht. f Pmoram 20 '/ f Acc-essing anay elements in difierent ways ti main( ) { int numll = { 24, 34. 12,44,56, '17 } : inti=0; while (i<= 5) { pdntl ( address = %u ' , &numll) i printf ( 'element = %d '. num0 ) ; pdntf ( '%d ', '( num + i) ) ; pnntf ( 'Yod ', '( i + num ) ) ; printf ( 'Yod', ilnuml) ; i++ i ) ) The output ofthe program would look like this: addrcss=400'f elerrefi.=z4 24 24 24 address = 4003 elemeot = 34 3}1 34 34 address = 4005 ehrnefi= 12 12 12 12 address = 4007 element = il4 '14 '14 44 address = 4009 element = 56 56 56 56 address = 4011 *n,e,rt= 17 17 17 17 More Than One Dimension So far we have looked at arrays with only one dimensio[ It is also possible for arrays to have two or more dimensions The two; diftensional array is also called a mafix. Here is a samnle progam rhal initialises a 2-D array and print, orai;.1".;"; ""'' f Prcgrcm21|'t maino { int stud[s][2] = { 11234,561, 1t212,331, { 1431, 80 }, 11312,78), 11203,751 ); int i, i; for(i=0;i<=4:i++l { prjntf(h,); ,or(j= 0i j<= , j++) pdntf('yod .,stud[m); l ) Look ar rhe pritrtf( ) statemelt... printf ( 'Yod ', studlr[l ) j 11, "+lltt{] fie trIsr subscripr is row nunber. The second EuDscnpl te s wbich ofthe two colurDtrs arE we talking about... thi 11oth c9tryn or_the frst colum- Rem€mber tfr"i".rrti'og oimws and columns begins witb zem. Thc complete array arrangerneat is sho*n hlour
  • 31. 54 lJnderstanding Pointers In C Chapter 2: Pointers and Arralts 55 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] ) ; we expect the Od elemetrt to get priated aod tbe 06 elernent is a 1- D anay. We know that just m€trtiodry a l-D array gives its base address. Herce the printf( ) would print base ad&ess of the 0d l- D anay. Similarly, stud[l] would give address of lr l-D aray and so otr. This fact can be illustrated by the fo[owing program: .r Pl0onn22'l . /f ReferfgurB 2.3 given in 0E pGvixBsectbn'/ Vl maino Lt' in, rtuotsltzl= ( ( 1234.56 ), 11212,331, { 1434, 80 }, { 1312,78}, { 1203, 75 } ]; inti,j; for(i=0ii<=4;i+i) pdntf ( "hAddress o, ,6d fi 1D any = l6u', ;, sM[l 1 , ) And here is the output... Address of 0 th l-D aray = 4001 Figure 2.3 'I1rus. 1234 is storEd in stud[0][01,56 i8 stored iD studlollll and t" "o. fnt above arraogcment highlights the hct that a-two- dime[sional array i6 trothing but a collection of a number of one- dimensional arrays plaoed orc after oother' 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 tfr"." "* no -tit *A cohoms' to memory whe&er it's a l-D or a i-o "r-y At at-*ta are stolpd in one continuous chain' Pointers and Two Dimensional Arrays Catr we not tef€r elem€Dts of a 2-D afiay usitr8 poinlEr notatioil' the wav wc did itr ooe{imeDsioDal anay? ADswer is y!s' only me prociure is slightlv dimcdt to urderstand- t'et us see how' The C language embodies e uousual but pow-€'rful capability: it ".n treat pirrs of an anay as aEays' MorG 4ccifiGally' each rortr ot ,**"--a]i.*i"J "t-i' * & thought as a one-dimensioDal arrav. Ihis i8 a very iEportaut fact if we wish to access aray el#ents of a twodimersioul array using pohters' Thus, fie declaration, ' int stud[51t2] ;
  • 32. 56 Undersnnding Pointers In C Address of 1 th 1-o aray = 4005 Address of 2 th 1-D aray = 40 ) Addrcss of 3 th 1-D aray = 4013 Address of 4 th 1-D an-ay =,1017 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 of the 2-D array. Heoce the exprglgiorL4itud-+-0 L€iles tN the ed.iress of Ge 0" elemeot of Ee 2-D aray. Naturally. lheadrl'ess of the 0d elemeot of the 2-D atay, I element. But the Orh elemefi ofthe 2-D array is a l-D aray- And on mentioning l-D would givs base addtEss oft- l-D anay. '(stud[2] + 1 ) '(-(stud+2)+1) Using *ese concepts the following Eogram priDts out each element of a two-dimensional aray using poirter notation. f Pnlftn23'l main0 ( int studl5ll2l = { { 1234, s6 }, 11212,331, { 1434, 80 }, {1312,781, { 1203, 75 } ), inli,jj for(i=0;i<=4;i++) t printf("h'); for (j= 0;j<= 1 ;.i++) . printf("70d','(-(stud+i)+j)); l ) And here is the oiitput... array we get its base address. Heqqg j(!]E4! jllLLtygqlhe base addrcss ofthe 06 l-D array. Referring to Figure 2.3 this rums oul io be 4ffiI:Timilady, caD you interpret the meaning of studlll (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 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 array we get its base ad&€ss, *( stud + I ) gives base address of lsr t-o,arravW)) 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 ad&ess ,1009, the address of lhe second one-dimensional array. Obviously ( ,1009 + 1 ) would give the sddEss 4011. Or 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 ). But, we havc alncady mt€d wtilc learuing l-D &rays that numlll 1234 1212 1434 1312 .l203 80 78 75 is sam€ as r(E!n + l). Simi :( ttd[2] + l) ie same as, 6ffissions referio the srtdt2ll1
  • 33. Pointer to an ArraY The way 1,,e cao have a pointer to atr integ€i, or a pointer to a float, "u, *" ulio have a pohter to an array? The answer is yes Declaration of a pointer 1o atr array, however, is a little clumsy For examole. the declaration Lrt ( *q )l4l Eeans tbat q is a poitrter ,o on orr& of4 itrtegers. Let us use this pointer to an army in a Eogram. Herc it is. . . I Pmgram 24 '/ main0 { iit alll4l= { 5,7,5, 9, 4, 6, 3, 1, 2,9.0,6 ); p=(int )a; q=a; pdntf ( 1n%u %u', p, q ) : p++: pdntf ( 1no/ou %u', P, q ) ; ) whereas, q statts pointing to the text 1-D aray of 4 integers. 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. almv to a 1,2,3,4, 5, 6, 7, 8, 9, 0, 1,6 int'p; int ('q )l4l ; And here is the output... 65500 65500 65502 65508 To begin {.ith both p and q contain the same address 65500' 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, Passing 2-D Ariay to a Function There are thtee ways in which we can pass a 2-D function. These at€ illustrated iD the following program. f Program 25 '/ f Three ways of accessirE a2-D a,ra(.'l #include <alloc.h> main0 ( int aB[ ]E_ { ); clrsc( ); disphy (a,3,4); show ( a, 3,4 ) ; pdnt(a3,4): ) display ( int 'q, in row ir[ col ) { inti,j; for(i=0;i<rcy;i++) { for (j = 0;j<col;i++) Pnntf ('old',' ( q + i'col +i ) ) ; printf('n'); )
  • 34. 60 Understanding Pointets In C Chapter 2: Pointers and Arravs 6l 1234 5678 9016 1234 5678 9016 In the displd ) ftactioa we have collected the base address of the 2-D array beiag passed to it in an odinary itrt pointer. Then through the twoJor loops using the expression * ( q + i * col + 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 r[2] J3l- Let us see whe6er the expression * ( q + i * col + j ) does grve thrs elemenr oihol Refer Figure 2.4 !o uDderstand this. printf (1n' ) ; ) show ( intfq)141, int roll, int col ) { inti,j; int'p; lor ( i= 0; i< row;ir-i ) { p=q+i; for(j= 0;j<col;j++) pdntf ( Yod ', ' ( p+j) ): pintf (t'); ) prinlt('n'); ) pdnt ( i;t q[ ][4], int Dw int col ] { inti,ji for(i=0;i<rorv;i++) { fq(J=0;j<cot;j+) pdntr ( '96d ', q[][! ) ; pdntf('Vr'); ) pdntf("h'); ) And here i$ the output. . . 1234 5678 9016 4001 4003 4005 4007 4OO9 40tt 4Ot3 4Ot5 4Ot7 4}tg 4O2t 4021 Figure2.4 l'he expression * ( q + t * cot + j ) becomes * ( 400f + 2 * 4 + 3 ).'l'his tums out to be * ( 4001 + ll ). Since 400I is address of an inleger, * ( 4001 + tl ) tums out to be * ( 4023 . Value at this oddress is 6. This is indeed same as e[2][3]- A more general lbrmtrla for accessing each array element would be: r ( base address + row no. t no. o, columns + column no. ) ln the show( ) function we have defined q to be a pointer to an lnay of 4 integers through the declaratiorx
  • 35. (Jnderstanding Poinlers In C int (.q )lal ; 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 int pointer, and then using lhis pohter all elements ofthe zercth I - D alay are accessed. Next time thrcugh the loop when i takes a value lf th€ exprdssion q + i fetches the address of tho first l-D 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. In the third tunction print( ), the declaration ofq looks like this: intqll[4]: This is same as int ( rq )[4], vhere q is pointsr to an array of 4 irltegefi. The only advantage is that we can rrow use the more familiar exEession q[il [] to acce$s array eleEreflts. We could have used the sarne expEs$ion in show( ) as well. Three Dimensional Arrays Consider the following array declaration: int a[3]l4ll2l = { { 12,41, {7,8 }, i3' 4 ). i5,6 ) Chapter 2: Pointers and Atays 63 {2,3} ), { (8,e)' 17,21, { 3.1}, {5,1} ) ); 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, each of whicb is a twodimensional aray of four rows. each of which is a one-dimemional array oftwo elemehts. In other words, a onedimeosiona!_array oftwo eleDents is constructed first. Then four such ooe-dimeisional arrays are placed one below the other to give a two-diDensional aray containing four rows. Then. three such two{imeDsioD4 arays are placed ore behind the other to leld a theedidensional aray containing three 2-dimensional arrays. In the array declaratioo note how the commas have been given. Following figune would possibty help you in visualising the situation better. xd 2-D Alray tn 2-D kr.y on 2-D Array 62 ), { {7,6 }, i3,4 ), i5,3 ), Figure 2.5
  • 36. 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. Figure 2.6 How would you reler lo the array element I in the above array? The first subscript should be [2], since the element is in third two- 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 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. Can we not rcfer to elements of a 3-D array using the pointer notation instead of the subscript notation? Certainly. Let's first begin with a simple Eogram- /t Program 26 -/ maino { int aPl[3][2] = { { {2.41, 17.8'^). {3,4} ], ]; printf ("n%u", a); printf ( 'nolou', .a ) ; printf ( 'b%u', -a ) ;. pdntf ( lno/od', *a ) ; printf('ho/ou',a+1); p ntf { 'n%u', 'a + I );kLprintf('h%u', *a + 1); ' printf {"n%d', *a + 1);j . ) Figue 2.7 shows the arangcment ofthe 3-D aray in memory. Figure 2.7 And here is the output ofthe prografi... .l04 t0r t0{' I ilt t0r t0r {2,2}, 12.31, {3,4} 06 2-D arlzy-+- t, 2-D array 21417 8 3 4 2 2 2 3 3 4 104 106 loa ll0 ll2 ll4 116 I18 120 t22 124 126
  • 37. 66 IJnderstanding Pointers In C J Referring Figure 2.7 it's not difficult to imagirc why the first prtntf( ) pdtrts out 104. However, the outsut of second and thftd pritrtf( ) is a little supiisiry. Let's try to undflstaod it Each element ofa 3-D au'ay is a 2-D aEay. Once the 3-D aray i8 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 that on mentioning a 2-D array we get its base address hence the second pri f( ) outputs 104. what about tfre exprEssion **e? *r gives poiater to zeroth element of the 2-D an'ay, h€na€ **a would give the zeroth eleme . But the zetdflr elernent ofthe 2-D aEay is 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 try to alalyse the output ofthe next prirtf( ) statement a gives the aidr".r oi znroflr i-D arra% therefore, . + I would give the addrcss of fiIst 2-D aray, which as per the fgure is 116. Can you now imagine the output ofthe rcst ofrhe prhtf( )s? Try it. ), { Passing 3-D Aray to a Function There are thrce ways i4 which we oatr puis a 3-D atray to a function. These are illustrated below. f Pmgram 27 ./ f Three ways of passing a $D anay b funclixl '/ main0 ( int i, j, k; jnt a[2]Pl[4] = { { 1,2,3,4, 5,6,7,8, 9,3,2'1 2,3,5,7, 4,3,9,2, 1,6,3,6 ] ); clrcc( ); display (a,2,3,4 ); show (a, 2, 3,4 ) ; print (a,2, 3,4 ); getch0; ) display ( int rq, int ii, 'nl ii, int kt ) ( int i, j, k; for(i=0;i<ii;i++) { br(j= 0;.i<X; j++ ) ( for(k=0;k<kk;k+t) pnnf ('%d','(q + i'jl'kk+ j'kl+ k) ) ; printf ( 1ll" ); ) printf(1n'); ) pdnf ( 1n" ) ; ) show ( inl ( -q )Bl[4], irf ii, imii, int kk ] (- int i, j, k; int'p i for(i=0ji<ii;i+r) t
  • 38. for(j=0;i<ji;j++) { p =c[][]; for(k=0;k<kk;k+) Pdntf ( '96d ', '( P + k) ) ; printf( 1n' ) ; ) printf('1n'); ) ) / print ( int q[ ]l3l[4], int ii, inl ii, int kk ) "r'1 int i, j, k; for(i=0;i<ii;i++) { forlj=0;j<ii;j++) { for(k=0;k<tk;k++) pdntr ( %d '. q[]D[{ ) ; pnff (l" ) ; ) pnnf('1n') ; ) ) And h€re is the output... 123 4 5678 932'l 2357 4392 1636 1294 5578 Understanding Pointers In C Chapter 2: Pointers and. Arrays 69: 932'l 4392 IOJD 1234 5678 9321 2357 4392 'I 636 The wotking of lhis progre ir same as that of kogram 25 discussed earlicr. HeDcc all ftar I yrduld do here i,s explain how q has been declared in each fimctiol Table 2.1 Returning Array from Functiin Now that we tnoq, how to pass a 2-D ot a 3-D aray to a firnotion, let us find out how to r€tultr a,l array ftoItr a fuDotio[ Therc are again three methods to aohieve this. Suppose we wish to retum a 2-D anay of integers from a function we caa rcfum the base addrcss ofthe array as: - A pointer to an integer - A pointer to the zeroth l-D array - A pointer to the 2-D aray 41lq )t3lt4l 'qis a poitrb to a 2-D snv of3 rows md 4 columns iDt qt lt3l[4] q is a]6iqt€I ro a 2-D sray of3 rows ird 4 coluotrs
  • 39. This is shovn in the followitrg ptogram. The firdctior futrl( ) reltrms the base addrcss as pointEr to integor, the function fuD2( ) rgturns it as pointer to zerolh l-D aray, whereas fun3( ) retums it as pointer to 2-D array ofhtegeN. Note the prototype declarations of the functioDs caefi ly. f Prcoram 28 '/ I Th;e ways of lBtuming a 2-D aray tun a funclion */ #defne ROW 3 #defne COL 4 main0 { int i, i; tint'a;. int'tun10: int ( 'b )ICOLI; iirr ('f,ii'20 )poll; int -p; int ( 'c )lRowlpol-l : int ('tun3( ) [RoWIcoLl ; cllEc( ); a=tun10; pdntf ( hAray allll in mai( ):W ) ; lor{i=0;i<ROW;i+r) l' for( i= o;i< coL:j+) printf ('%d';'(ar i'col+ j )) : pdntf(1r''); ) setch( ) ; b = fun2( ) j printf ( "nArEy bl l[ J in main( ):h. ) ; for(i=0;i<ROW;i++) { p=b+i; for ( j= 0; j< COL 'i++ ) t prjntf(t/od',.p); p++; ) pnntf ( "Vr') ; ) getch0 j c = tun30; / printf ( "h&ray d l[ I in mdn( ):W ) ; for(i=0;i<ROW;i+[) { for(j=0'j<COL.++) pdntr( %d., (.c)[ilUI) ; pintf('rf); ) getch0 j ) Int.fun10 ( shlic int alRowlmrl = ( 1,2,3,4, 5,6,7,8, 9, 0, 1,6 ); inti,i;
  • 40. "2 Understaading Pointers In C pintr ( lnAmy a[ [ I in tunl( )M ); for(i=0;i<ROIIV;i++) { tor (i = 0;i< COL 'i++ ) pintr ( 'r6d ', al i lli I ) ; pintf( 1n' ) ; ) retum(int.)a: ) int ( 'tun20 )lcotl { shtic int blRoll'{mq = { . 9.4' 6' 4, 1,3'2'1, 7'5, 1'6 ); inti, j ; pdntf ( tAray bt l[ I in tut2( )rtr' ) ; for(i=0;i<Rqw:i+l) { tu (i= 0; i< col;F ) pintf ( *r6d " btilil ); pnntf ( t'); ) rctum b; ) int ('fun3( ) )[Rou,tPOLl { static int ctRolfulcou = { 6. 3, 9, 'l' 2,1'5,7, 4,1,1,6 ): Chapter 2: Pointers and Arrays 73 inti,j; printf ( 'hA;y cl II I in tun3( ):h' ) ; for(i=0;i<ROW;i++) { for(j=0;i<COt;j++) printr('Y!d', cl i ltj I ) ; pdntr ( 1n'); ) retum ( int (' )[ROl'vllCOL] ] c ; ) And here is the output- . . Aray a[]llintunlo: 1234 5678 9016 Arlay al l[ ] in main( ): 1234 5678 9016 Anay b[][] in luo2( ): 9464 1321 Anay b[][]in main( ): 9464 1321 7516 Anay c[][]in tun3( ): 6391 2157
  • 41. lJ"dntnndl!E!9!!!9o I" C - Chqtei 2: Pointers and Arrays Zj 4116 Aray c[ ][ ] in main( ): 63S'l 2157 4116 Returning 3-D Array from a Function 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 four possible *ays to do so would bG to retum the base address as: - A pointq to ali integer - A pointer to ihe zeroth l-D array - A pointerto the zercth 2-D array - A poitltcl to the 3-D ariay Given below is the pDgram, which ifiplemeDts these four ways of retuming a 3-D array. f Program 29 '/ f Four ways of retuming a $D aray film a funclion .l *idefne SET 2 Itdefne ROW 3 #deline COL 4 maino { inti,j,k; int'a; int-fun'lO; int ( .b )lcotl ; int ( 'tun20 ){coLl : int ( 'c )lROaTCOLl ; int ( 'tun30 )lRol'uporl; int.p; int ( 'd )lSEIllRoW[coLl; int ( .fun40 )lsEr]lRovupoLl; clrsc( )j a = fun10; pdntf ( lnAnay a[ I[ [ I in mai( ):W ) ; for(i=0;i<SEI;i+i) { for(j= 0;i < ROW; j++ ) { for (k = 0;k < COL;k+r,/ pdntf('96d','(a + ir RCIW'COt +j. COL + k )) j printl ( 'h') ; ) pdntf(1n'); ) getch0; b = fun2{ ) ; printf ( 'nAn-ay b[]Ull in mJn( ):h' ) : fol(i=0;i<SET;i++) ( p=(inl,)(b+i.ROlfl); for(j= 0;i < Row;.1++) { for(k=0;k<COL;k+r) { pdntf ( '%d ., .p ) ; p++;
  • 42. 76 Unilerstanding Pointers In C ) pnntf (1n'); ] pintf('h'); ) ttro; c = tun30; pddtf ( 'nAray c[ ][ ][ I in main( ):W ) : for ( i = 0; i< SEI; i++ ) ( p=(int')(c+i); for(i=0;j<ROW i+t ) I ' for(k=0;k<COL;k+[) { pnntf ( '9{d ', 'P ) ; p++; ) pdntf ( 1n') ; ) pnntf (l') ; ) getch( ) ; d = fun40 ; p ntf ( 'hAray d[l[l[] in main( ):W ] ; for (i= 0 i i< SET;i++ ) { for (j = 0 ;j < ROI,V ;j++ ) ( Chapter 2: Pointers and Arrays 77 for(k=0:k<COL;k++) pdntr('%d ', (-d )[i][i l[ k l); pdntf ( 1n'); ) printf("n"); ) getch( ) ; ) int. tun10 {' inti,j,k; static int alSEIllROVtIllCOLl = { { ) ); pdntf ( "hArmy a[ ]l lll in tunl( ):Vr' ) ; for { i= 0 ; i< SET; i++ } { for (i = 0 ;j < ROW; j++ ) { for(k=0;k<COL;k++) printr { '%d ', ali ltj llk I ) ; printf(ln'): ) 1,2,3,4, 5,6, 7, 8, 9,3,2,1 2,3,5,7, .4,3,9,2, 't, 6. 3. 6 ), {
  • 43. 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, int ( 'fun2{ ) )ICOLI 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'): printf ( '%d ', bti[i]lkl]; ) 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 = { {
  • 44. 80 Understanding Pointers In C Chapter 2: Pointers and Arrays 8l ) ); printr ( "nAray d[ ][ ][ ] in tun4( )ln' ) ; . for ( i = 0 ; i < SET ; i++ ) { lor (j= 0;j< ROW jr+) { lor(k=0;k<COL;k++) pintf ( '96d ", dliltjllkl); pdnd(tu"); ) printf('Vr'); ) return ( int (t )lSEIllROWlcoLl ) d ; ) And n"ere is the output... Aray a[][][] in tun10: 123 4 5678 9321 2357 4 392 1636 Aray a[][][] in main( ): 1234 5678 932'l 2357' 4392 1636 Anay b[I][Iin tun2( ): 9464 1321 75't 6 6391 2157 4116 Anay b[][][jin main( ): 9464 '1321 7516 6391 2't 57 4116 Anay c[]ll[]in tun30: , 3185 0652 2016 7 327 1423 0106 Aray c[][][]in m;in0: ), { 3, 1,8, 5, 9, 6, 5, 2, 2,0,1,6 7,3,2,7, 1,4,2,3, '9, 1,0, 6 i
  • 45. 82 Understatding Pointers In C Chapter 2: Pointers and Arrays 83 3185 9652 2016 7 327 1423 9106 Aray dll[]ll in tun40: 1705 2391 5116 cJ I / 1423 Anay d[][][]in main( ): 1705 2391 5116 5317 1423 7 216 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 but a colleclion ofaddrEsses. lae adclresses preselrt in the alray of pointers oan be addresses of isolated variables or addresses of array elemerfs or any other addresses. All rules that apply to an ordirDry array apply in toto to the array ofpointeN as well. I think a prograrn would cldiry the concept. f Pmgram 30 .i main( ) { int 'ar[4] ; f fiay of inhg€r poinbls '/ int i= 31, j= 5, k = 19, t= 7t, m . an[0] = Ai; an[1] : &.i ' anl2l = &k; art3l = &l ; for(m=0;m<=3;m++) pdfltf ( 'h96d', '( adml) ) ; ) Arld here is the ou&ut... 31 5 71 0' kl l-,,1 l--;l l--rl l=-l4008 5116 6010 7I l8 ad01 adll a"IL2I 4008 5116 60lb )r ra 7602 7@4 7@6 ant3l Figure 2.8
  • 46. Understanding Pointers In C Figure 2.8 shorns the contents atrd the arangement of the array of pointeN in memory. As you cal obwrve, arr contains addresses of isolated lDt variables i, J, k and l. The for loop in the plog1am picks up the addresses present in arr ard pdEts the values prcsent at these addresses. An array of poiaters can evetr contain the addresses of other arrays. The following plogram wouldjusti! tltis. /' Pogram 31 '/ maino t static int all = { 0, 1, 2, 3, 4 }; shtic int'p[] = {a, a + 1, a +2, a +3, a+4 }; printf ( ln'/ou %u 96d', p, 'p, '( 'p ) ) ; ) I would leave it for you to figurE out the output of this program. An array of point€rs is very popularly us€d fol sioring several strings in manory, as you would see in tlre next chapter' Dynamic Memory'Allocation Coosider the array declaratioi, int ma*s[100]; Such a aleclaEtion would typically be used if lqoinldent's marks were to +e stored itr memory. The moment we make this declaration 200 bytes aIe rcseped in memory for stoling 100 integers in il HowEver, it may so happen that when v/e actually run thd program. we might be inteEsted in storing only 60 student's marks- Even in this case 200 bytes would 8et reserved in memory, which would result in wastage of memory. 84 Chapter 2: Pointers and Arrays 85 Other way rouad there alwa]rs exists a possibility that when you rrn the program you Deed !o store more ihatr 100 student's marks. In this case the aray would fall short in size. Moreover, llpre is no way to inqease or decrease thqauay size-dudng-crGeq![q4-!t][ the 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 rhe dme of executioo? This -is datrc__Jsl[g* standard [trary furctions mill^.( ) and catloc(J. Since these tunotioos allocate memory on the- fly (during executiotr) they are-oftentno",t1 as 'Dyramic meinorjr allocation functions=) L6t us now see a program, which uses the corccpt ofd)mamic memory allooation. f Program 32 ti #incude ?lloc.h' main0 { hl n, avg, i,-'p, suo = 0; pintf ( Enter tle number of studenb ' ) ; scanf('%d', AD); I p : ( imr) rnathc ( n | 2 ) ; ly ir(P==xuLLl --- { pinu ( 'h lemory allocaton unsuccessqE) ; eit( ) : ) for(i=Q;ifn;i++) scanf ( "96d', (p+ i)); for(i=.0ii<nii++) sum:sum+.(p+i); avg=sum/o; printf ( "A .......ge mafts =%d', aW ) ;
  • 47. 86 e 4arks. Not a byte more, not a b,'te integgr pointsr.p. Sfuce mr[oc( ) Etums a void pointcr we have t r""ur[a it into aa integer poiorer. lo Ee first for looE-!!]iIJ ti-"ii6-i"ttt aritlrne6rcwe tave storrd the marks ent!:red from keyLoar{ulqlhe rn.-ory -that h* b""n allocated. In the tecond for loop-we have 4ccessed the same values to fitrd the avemge marks. The calloc( ) functioos works exactly similar to Erlloc( ) except for the faot that it needs tw-o atguments. For example, inl'p; p= ( int') calloc ( 10, 2 ) ; Chapter 2: Pointe$ and Arrq)s gZ Solved Problems IAI What will be the ouFut oflhe following progiams: (1) main0 ( int a[] = { 10, 20, 30, 40, 50 } . intj; tor (j =p ;j < 5;j++ ) t/ printf('hyd.,t); a++; ) ) O tput Emr message: LvaftJe tequirEd in fundfun main Explanation ,Here, we have fiIs! asked- for the number of studelEwhose-4alks are tgbe eltqed-ard lhelalloqated 9ub/-"1-qt!ch rnemory as is 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 address. Therefore, firsltt!rc flrcugh the loop; the Dritrd( )differeDce between mdto( ) and crnoc( ) is tbat' by defaulrlllhe address. l[erelore, trslttll! though the loop; the pritrtf( ) should print the value at this-bae€ ai[li&-s.-fr;iE ls nomemory Sn co oat attocatea ty dtoi@s' s11 :Ers. wA& u!!g thrse problem up to this. The @ ies ln tEe oext statement, an allav- the only thing thai it l€rnembers about an array oace declared ii"i""-i-r.",*.*d 6^ tr" GpnFit-*" begimiggof-*c'@lgaur. 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. .
  • 48. 88 Understanding Pointers In C Chapter 2: Pointers and Arrays 89 (2) maino { foat all = { 13.24,1.5,1.5,5.4,3.5 }; ioat l, 'k; 1j=,;k=a+d; j=j'2i k=kl2', printf ( 1n%f%1, 'j, 'k ) ; I Olttpu, Eror message: lllegd tse ol Finler in tunction main Explatatiott i atrd k have b€en declared as pointer vafiables, wbich would contain the addx€sses of foats. In otler words. j and k are Iloat poinlefs. To b€gitr with, the base addrcss of the array al I is stored io j. The ner(t statement is perfectly acceprablel flr. "aaress offte 46 trort fiom lhe base addrEss is storcd in k. The next t$'o stat€rne s arc €rroneous. Thrs is because the only operations lhat can be performed oa pointers are addition and subtaction Multiplication or division of a pointer is IIot allowed. Hence lhe error message. main0 { nlol = 100 ; nl24l = m0; pnnf (t%d 96d', -n,'( n + 24 ) +'( n + 0 )) ; ) Outpat 100 300 Explanation n[ ] has bein declared as an array capable of holdirg 25 elements [umbered ftoln 0 to 24. Then-100 and 200 are assigned to n[0] and r[Zl resp€otively. Thetr comes the most impolant pa -the prhtf( ) statemed Wheaeyer we mendon the name of the array, we get its base address (i,e. address of lhe zercth elqlre of the array). Thus, *n would give the value at this base addness, which itr this case is 100. This is theD prhted out. Look at the rcxt expression, -(n+24)+'(n+0) n gives the address of the zeroth element, tr + I gives the address ofthe next el€rtre ofthe array, atrd so on. Thus, n + 24 would give the address-ofthe last elemetrt ofthe array, and therefore *( n + 24 ) wonld give the value at this ;itdress, which is 200tu our case. Similady, *( n + 0 ) would give 100 and the addition of the two *,ould result hto 300, trhich is outputted nexl main( ) { int b[] = { 10, 20, 30, 40, s0 }; int i, 'k; k =&b141-4; . for(i=0;i<=4;i++) { pnntf ( 'Yod ', 'i( ) ; k++; (4) (3)
  • 49. 90 Understtnding Pointers In C Chapter 2: Poinlerc and Arrays 91 Output 10 20 30 40 50 Expldnatio Fi$t look at Figue 2.9. The aEay elements are stored in cotrtiguous memory locations ard each element is an integer, hence is occupying 2 locations. Figure 2.9 The expression &b[4] gives the address of b[4] (4010 in this oase)- From this addEss ifwe zubtract 4, we get 4002 Or did you expect to get 4006? Remember that by subtracting 4 fiom 4010 what ltre mean is ge ss ofan integer, which is 4 integeE to the left of the integer whoG-addii:ss is 4010. No$r', address of the i teger, whibh is 4 htegers to the left of the irteger whose addrcss is 4010, is the ad&ess 4002 This 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 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 tlrough th€ for loop *k would yield the value at address contained ia k, i.e. value at the address 4004, which is 20' Similarly, rhe loop priots out the Iest of the elements of the altay. {5) main0 { char a{l = "Visual.C++' ; char'b = 'Visual C+' ; printf('no/6d %d', sizeol ( a ), sizeof (b ) ); pdntf ( 'ln96d 96d', sizeof ( 'a ), sizeof ( 'b ) ) ; ) Output 11 2 11 Explanation 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 b)4e. main0 { f Assume arEy begins at addess '1200 '/ int anll = {2,3,4, 1,6 ); pdntf ( '%u %d', an sizeol ( ar ) ) ; ) Output 1200 10 Explanati6n there is a'0'sitting at the end. b is a pointer h-ce its size ;" I b)ts-5 atld *b both yield a charactei'V', whose size is one (6) b[0] btu bt2l bt3l bt4l 4lnm 4n0/. 4006 4008 4010 l0 20 30 40 50
  • 50. 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 elemetrts. each of2 bytes, sizr ofthe array is reponed as l0 bltes. Note thal except when used with sizeof( ), name of the array yields its base address. (7) maino { f Assume a.ray begirE at addEss 65486 '/ intar{l= { 12,14, 15, A,45}; pdntf ('%u %u', ar, &ar); 6printf{'%u %u'. ar+ 1. &ar+ 1):'t )E- Output 65466 65486 65488 65496 Explahalion Both arr and &.rT yield tire base addless of the array. However, rrrtl gives 65488, i.e. the address of the next integer. However, &rrr + I gives 65496, i.e. the address of the next array ofs inl€gers. (8) maino { I Assume array begirE at ddless 65472 '/ int al3il4l = { 1,2,3,4, 4,3,2,1, 7,8,9,0 )' pdntf ('h%u%u',a+ 1, &a+ I ) ; ) Outpat 65480 65496 bqlafiation Name of a 2-D arr.ay always acts as pofuter to the zeroth element of the aray. Since the zeroth element of our 2-D aray is l-D array of4 inlegers, a acts as pointer to this zeioth 1-D aray. Hence a+l gives us the ad&ess of the next l-D array, i.e. 65480. The expression &a + I yields 65496. i-e. rhe address of the next 2-D array of 3 rcws and 4 columns. (9) maino { f Assume array begirE at locdion '1002'/ int a[3][4] = { 1,2,3,4, 5,6,7, 8, 9, 10,'11,12 1; printf ("Vt%u %u %u', a[0]+ 1,'( a[0]+ 1 ],.('( a +0 )+ 1 )); ) - Output 1004 2 2 Explanation '
  • 51. 9594 Understanding Pointers In C Chapter 2: Pointerc and Arrays A 2-D airay is a coll€ction of several l-D arrays. Name of a 2-D aray always acts as pointer to zeroth elemeat of the almy. Hence, a acts as pointer to the zeroth l-D aray. The expression r[0] + I is hterpreted by the compiler as *( a + 0 ) + l. This is same as *a +1. The expression *a gives 1002. Thercfore, *e +1 would give the address of the next integer, i.e. 1004. Since a[0] + r yields 1004 *( a[0] + 1 ) would yield lhe value at address 1004, i-e. *( al0l + 1 ) can be expanded gs *( "( a + 0 ) + I ). Hence, both the expressions would yield the salne result, i.e. 2. (10) main0 { int al3l[4] = { 1,2,3,4, 4,3,2,8, 7, 8,9, 0 ); int'pf; ptr = &a[o]pl ; lun ( &pt ) ; ) tun (int *p ) { printf ( 1nyd', 'p ) ; ) Output 1 Explanation Here, in ptr we bave stored address of l. Then we have passed ad&ess ofptr to fun( ) and collected it in a pointer to an itrt pointer- Dereferencitg this pointet yields l. ('11) maino { f Assume a.ray begins at location 1002 */ int a[2]Fl[4] = { ( 1,2,3,4, 5, 6, 7, 8, 9,1,1,2 ), { 2,1,4,7, 6,7,8,9, 0.0.0.0 ) I' prjntf ( i%u %u %u 96d', 4 *a, *a, *a ) ; ) Output 1002 1002 1002.'l Explan .tio., - The expressions a, "a, *ra, would give the base addrcss, i.e. 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 (12) main( )
  • 52. 97 { int a[]= { 2,4,6,8, 10 }; int ij for(i=0;i<=4;i+t) { '(a+i)=a[]+ilal' printf('%d',t(i+a))j ) ) Output 4812 1620 Explatation Imbibe the following three frcts and the program becomes very simple to undeistaud: - Mentio ng the name of the array gives the base address oI the array. - AIIay elements arc stored in coDtiguous memory localions. - On adding I to the address of an integer, we get the address ofthe next i[teger. Wilh rhose factrs clearly laid out- let us oow try to undeNtand the program. Remember that infemally C always acoesses an:ay elements usi[g pointers. Thus, when we say a[i], 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 + i ) is same as *( i + . ). Therefore a[il must be same as i[al. Thus a[i]. *( a + i ), *( i + a ] and ilal refer to rhe same element lbe ih element from the base address. Therefore, the expressior used in the for loop, *( a + i ; = a111 + ilal is nothing but alil - alil + alil- Thus all that is done in the for loop is, each aray element is doubled and theD printed out through printfo. (13) main0 t int alsl = { 2, 4, 6, 8, '10 }; int i, b= 5; for(i=0;i<5;i++) { f (alil, &b ) ; pdntl { 'h%d 96d', a0. b ) ; ) ) f (int x, inl -y ) { x=*(y)+=2; ) Output 27 49 6 11 813 10 15 llxpldhaaon After initialising the array when the control enteN the for loop, the fimction f( ) gets called with value of a[i] and addrcss of b. In f( ) these are colleoted in vadables x and y. Then comes the exptession r = *( y ) +- 2. Here *( y ) += 2 is
  • 53. 98 Understanding Pointers In C Chapter 2: Pointers and Arrays 99 (14) evaluated fiIst and thell the Esult of this expression is assigned to x. The first time thmugh the for loop *( y ) gives 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 f( ), b's value keeps getting updated, whereas therc is no change iD the values of the array elemenh. Figure 2j10 main( ) { int alsl = { 2, 3, 4, 5, 6 }; inti; change (a ); lor(i=4;i>=0;i-) pintf { 'Y"d ', a[]) ; ) change ( int'b ) { inti; for(i=0;i<=4;i++) t 'b='b+1; b++;ri ) ) Output 76543 Explsnation Figue 2.1I While caling charye( ) we are passing the base address ofthe aray, which as per Figure 2.ll is 4002. This address is collect€d in b in the functioo change( ). Then the oontrol enters the for loop, where we meet the explession *b = *b + 1- This means rcplace the value at the address contained in b, with value al the address contained in b plus 1. Every time b+ is executed, the address ofthe trext integer gets storcd io b. Thus, using the address stored in b, we get an access to aray elements that are now changed to 3, 4, 5,6 and 7. Oce the control comes back from change( ), the current array contents are then printed out ftom end to begindng through the for loop. 401 E f , I b l-5 I 4008 atol alll al21 a13 441 4co2 4004 4M ,1008 4010 bb [ 4oo, I b--,[ 4oM I
  • 54. 100 Understanding Pointers In C (15) mainO { int arll= {0, 1,2,3,4 }; int,pb; for ( ptr = &ar{01 ; pt <= &ant4l ; ptr++ ) printf ( '%d ', tpr ) ; ) Output 01234 Elplanation Refer to Figue 2.12 lot a better utrderstanding of the pIOgram. Here ptr has been dectared as an integer pointer, i.e a variable capatle of holding the address of art integer. In the for loop, irl the initialisation part, this ptr is assigned the address of the zeroth elernent of the integer aEay Suppose 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 for loop, the address storcd h ptr is compared with the addrcss of the foufh aray elemen! i.e. 6012. Sirce for the first time lthe, conditioa is satisfied (shce 6004 is less than 6012), the'cotrtsol reaches pritrtf( ) where the value at address 6004, i.e. 0 gits pinted. After executing priutf( ) the control reaches pff+, where ptr is incremented such that it contains the addrcss ofthe rext integer. Since the next integer is stored at 6006, pf now contains 6006. Once again the condition is tested- Since 6006 is also smaller lhar 6012, the conditiofl is satisfied honce the printf( ) prints out the value at 6006, i.e. l. And then pffi is executed again so that it corltains the Chapter 2: Pointers and Arrays 101 address of the next iateger, i.e. 6008. This prccess cotrtinues till all the array elements have beea prioM. arrl0l arrlll alll2l .Irl3l arltll 0 I , 3 4 6008 6010 6012 ptpts f eoor I o*, frooo I FigtuIe 2.12 (16) main0 (, int arl l= {0, 1,2,3,4}; int i, 'ptr; for (pb= &ar40l, i= 0; i<= 4 ; i+| ) prinf ( %d ', ptfl ) i ) Output 0123 4 Expla atiol . In the initialisation part ofthe for loop, multiple initialisations are being done. Fi$tty, ptr is set up vith the base address of the alIay and then i is set to 0. Since 0 is less than 4, the condition is satisfied for the first time atrd the control reaches printf( ). Here the value ofthe exprcssion ptr[iJ gets printed.
  • 55. 102 Understanding Pointerc In C Now ptrlil is nothiDg but r( ptr + i ). Sipce ptr coDBins tle base address of the arr6-ylptu t I ) would gi-E the address of the id irteger 8om the bas€ ad&ess. Since i is going to vary fiom 0 to 4, this would give addrcsses ofo", l''.2"o. 3'o and 46 integers ftom the bas€ addE$s of the aray. Naturally, the exFession *( ptr + i ) would give values at these addrcsses. Thus, the for loop would print out all the array elements. (17) maino ( int anll={0,1,2,3,4}; inl i, *p ; for( p = ar, i = 0 ; p+ i <=ar+4 ; PF[, i+r ) Pdntf ( '96d ', '( P + i) ) ; ) Output .024 Explanation The following figul€ would help in understanding the program. Chapter 2: Pointerc and Arrays t03 the initialisation part, p is initialised to trc base address of the array. whereas i is initialised to 0. Afier these inirialisations the cortrol rcaches the conditiotr. The condition is a little complicated so let us isolate it for a clearE u[derstanding. p+i<=alr+4 Here + enjoys a higher priority thar <=. Therefore, firct p + I afld arr+4 arc performed ard then tha <= goes to work. p+i yields 6004. wherEas arrH evaluates to 6012, SiDce 60Oa is less than'6012, the condition is satisfied and fte coIlhol reaches pr-intf(-), where value at ( p+i ), i.e. 0 gets printed. Thed the control r€aches the iacrernentation part of the for 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. Since the condilioo oDce again gets satisfie4 thi priut( ) pnnts out the value at ( p+i ), i.e. 2. Similarly, next time around 4 gefs printed aud then the corditiol fails therefore the execution is terminated main0 t int an[]= {0, 1,2,3,4}; int'pt; for ( ptr = an+4;pt'>=ar; ptr- ) pdntf ( 'ol'd ', 'pf ) ; Output 43210 Explanatioh (18) arrtol al'0l ard2l ad31 aq[a] 6004 6006 6008 6010 6012 0 I 2 3 4 Figure 2.13 ln the for loop frcre ee multiple initialisatioDs arld multiple iroremeDtatrons, each s€parated by the cornma operatol. ln
  • 56. Chapter 2: Poinlers and Arrq)s t0s Output 43210 The following figure would lead to a better understanding of the program. a'I[0] ar{ll ar[21 arrt3l an[4] 6010 6012 Dts PE I rorz I PE-- -l eoro Il-l I0 2 3 4 Pignrc 2.14 In the initialisatiotr part, ptr is assiFed the address of the last element in the array. This is because rrr+4 gives the addrcss ofthe fowth iateger Aom the bas€ ad&€$s. First time tbrough the looD the cotrditiotr evaluates to true, siDce the addless of the fourtlh elemeot (6012) would certainly be bigger thaD the base addrEss (60M) of the array. Next, the conbol reaches prhtf( ), wbi;h prints oltt the value at adiiress cortained in ;tr. i.e. "lue at addr€ss 6012. N€xl, the statement ptr- gets executed which reduces pk io 6010. Sirce 6010 is also bigger thar 6004, rhe condition is satisfied onoe again, ard the valu€ at 6010 gets printed through the printf( ). This process is lepeated for all the aray elcments. main0 { int arll = {0,1,2,3,4 }; inti,'pf; for(pb=ar+4, i =0: i<=4 ; i*) printf ( "t6d ', Pt[-il) ; ) Explanatio ar{01 a{tl aEl2l an[3] . a44l 60M 6006 6m8 6010 6012 0 I 2 3 4 Figure 2.15 The above figule shows the amngement ofthe array elements in memory- In the iiritialisation part ofthe for loop, ptr is assigned a value 6012, since arrH gives the addrEss of the fouth integer Aom the base address of the array. Here, the variable I is also initialised to 0. Siace th6 condition is satisfied for the first time (i being 0), the printf( ) prints out Ore vatue of ptr[-ll. But what is ptrl-il? Nothibg but *( ptr - t ). And since i is 0, *( ptr - i ) evaluates to *( 6012 - 0 ), i.e. 4. Then the control reaches i+ where i is incr€rnented to l. Nexg the condition is checked atrd sirce it evaluafes to true, the prini( ) pritrts out the value of pfr[-il. Since this time i is l, ptr[-i] becomes *( ptr - I ), i.e. *( 6012 - 1 ), i.e. * ( 6010 ). Thus rhe value 3 gets prinred. Likewise, 2, I ad 0 also get printed subsequent times though the for loop. main( ) { int anlj= {0, 1,2,3,4}; int tptr i (1e) (20)
  • 57. 106 Understanding Pointers In C for ( ptr = ar + 4 ; p&>= ar ph- ) . pdntf('%d ', ar Ipr- ar]]; ) Output 3210 Explanatiort A picture is worth a lhousaDd words. Going by lhis dictum. the follolving figure should add clarity to your understanding ofthe pmgram. Figue 2.16 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 Aom the base address. Since this address is gre.ter than tie base addrcss, the condition is $alisfied and the control reaches pritrtf( ). What does rrr I ptr - arr I evaluate to? ptr - arf means 6012 - 6004 which yields 4 and hence arr[4] prints out the fou h element ofthe array- Then ptr- reduces ptr to 6010. Since 6010 is greater than the base address 6004, the condition is satisfied and once again the conhol reaches the printf( ). This time ptr - {'r'becomes 6010 - 6004, i,e. 3. Thus arr[3] pdtrls out 3. This pmcess is repeated till all the integeft ill the array have been p.inted out Chapter 2: Pointers and Arrqts 107 Possibly an easier way of understanditrg the expression ptr - 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 logical 10 expect the result ofthe subtraction as 4. (21) main0 t static inta[]= (0, 1,2,3,4 ]; static int'p[] = {a, a + 1, a + 2, a + 3, a + 4l ; int .'ptr : p; printf ( "h%u %d", a, 'a ) ; printf ( 'olou %u 7d', p, 'p, *p ) ; pintf { ln%u %u %d", ptr, 'ph *ptr ) ; Output 6004 0 9016 6004 0 9016 6004 0 E,Vlanation Look at the initiatisatior of, the array p[ l. DuriDg initialisafion, the addresses of various elemenis oi th" ".r i a[] are stored in lhe aray p[ l. Sioce the array pl 1 contalns addresses of idegers, it has been declared as -ari arrav of pornters to integers. Figue 2.17 shows the conteats of arrays a[ ] and p-[l In the variable ptr, the base addrcss ofthe ariay p[ l, i.e- 9016 is storad. Since this address is the address of p[0], which itselfis a pointer, pti has been declarcd as pointer to an integerpoi[!er. Let us undelstand the first pritrtf( ) rcw. T. adoi arIlli anl2l alrt3] artal 0 2 3 4 6006 6008 6010 6012
  • 58. 108 Unilerstaniling Pointers In C printf ( "hy"u %d', a, 'a ) ; It prhts out the base address ofthe array a[ ] and the lalue at this base address. a[0] atll al2 431 {al 6004 p[01 6006 ptu 6008 pql 6010 pt31 6012 pt4l 60M 6006 6008 6010 6012 9016 9018 90m 9022 prr lg0'61 7888 0 2 3 Chapter 2: Pointen and Anays 109 Now onto tlle last printf( ). pdntf ( 'n%u %u 96d', pr, 'pr, *ph ) ; 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 address 60M, which is 0. (22) maino { static intalt = {0, 1,2,3,4 }; sbtic int'pU = {a a + 1, a +2,a+3,a+ 4}; int *Ptr = P' ptr++j a} pirfff ( 'n96d 96d j6d', pr - p, -pr - a, *pb ) ; ' 'Ptr++' printf ( 1n9{d %d 96d', pr - p, 'p[ - a, 'p[ ) ; l++ptr; pdntf ( 1n%d 9(d 9{d!, pr - p, -pr - a,-ptr ) ; ++.ptr; pdntf { %d 96d 9{d', pb - p, 'pr - a, 'pr } ; ) Outryt 111 222 344 Explanation Figure 2.17 Looking at the figsre, this u'ould turtr out to be 6004 and 0' when you execute the p'.ogram' the address may tum out to be somethfug other than 6004, but the value at the address would be surely 0. Now look at the second Pritrtf( ). pdntf ( 1n%u %u 96d', P, 'P, *P ) ; Here p would give the base address of the aray p[ l, i e' 9016; *p would give the value at this address, i.e 6004; **p would give the value at the address given by *p, i.e value at addrcss 6004, which is 0.
  • 59. 110 Undentanding Pointers In C Chapter 2: Pointers and Amays 111 work and increfienls value in ph to 9020. Now with ptr containing 9020, let us once again analyse the expressions ptr - p, *ptr - a and **plr'- . - Figure 2.18 plr-p Figure 2.18 would go a loag way in helping us to understand this prograno- Herc ph has beetr declared as a pointer to an integer pointer and assigoed-t[e base address of the array pt ]. which has been declared as an array of integer pointers. wllat happens when ptr+ gets executed? ptr lgiots ro the next inGger pornter rp the armv pll. b other words. now btr adfiIdin. tfia- adclress 9(r18. Now let us analyse the meaning ofplr _ p. *ptr - a and r*ptr. pk-p 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 - iis reducedto ( p + 1 - p), which yields l. tptr - a *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 epression become,s ( a + 1-.), which is nothing but l. ptr conlairs 9018, so *ptr yields 6006. and hence *+ptr becomes *( 60116 ), which yields I - Thus tbe ouPul ofthe firsf prhtf( ) becomes I I L Take a deep brealh atd then begin u,ith rhe analysis of*pt ++. Here * and r+ both are unary operalors. Since -- occurs aller the vadable, + would be dode later. Firstlv *(9018) is perturmed, but since this value is not beini assigned to any vafable it gets ignored. Next, ++ goes ti 401 altl at2 at3l al41 0 I 2 3 4 6004 ptol 6006 ptll 6008 Pl21 6010 6012 pt3l pt4l 6004 6006 6m8 6010 6012 9016 9018 9020 9022 9024 ( ptr ptr l f noro I ,'*',ft"l I7888. pts 7888 ptr f,file"t-f,mtl7888 PF 7888 pts llqo2o I .**ro,l-eo2tl 7888 pE ptr f ,Ell *-pt',fG7l .@bt" ?888 78BB 6012