0% found this document useful (0 votes)
10 views

C Pointers

The document discusses pointers in C and C++ programming, explaining their functionality and usage in accessing memory addresses. It provides examples of pointer declaration, reference and dereference operators, and how pointers relate to arrays. Additionally, it highlights common mistakes when working with pointers and demonstrates their application through sample code.

Uploaded by

Typhon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

C Pointers

The document discusses pointers in C and C++ programming, explaining their functionality and usage in accessing memory addresses. It provides examples of pointer declaration, reference and dereference operators, and how pointers relate to arrays. Additionally, it highlights common mistakes when working with pointers and demonstrates their application through sample code.

Uploaded by

Typhon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CPoi

nter
s

Poi
nter
sarepower
fulf
eatur
esofCand( C++)pr
ogr
ammingthatdi
ff
erent
iat
esi
tfr
om
ot
herpopul
arpr
ogramminglanguagesl
i
keJavaandPy
thon.

Poi
nter
sar
eusedi
nCpr
ogr
am t
oaccesst
hememor
yandmani
pul
atet
headdr
ess.

Addr
essi
nC
Bef
orey
ougeti
ntot
heconceptofpoi
nter
s,l
et'
sfi
rstgetf
ami
l
iarwi
thaddr
essi
nC.

I
fyouhav
eav ar
i ev
abl ari
nyourpr
ogram,&varwi
llgi
vey
oui
tsaddr
essi
nthememor
y,
wher
e&iscommonlycall
edt
heref
erenceoperat
or.

Youmusthav
eseenthi
snotat
ionwhil
eusi
ngscanf
()funct
ion.I
twasusedi
nthe
funct
iont
ost
oret
heuseri
nputtedv
aluei
ntheaddressofv ar
.

scanf (
"%d",&var);
#include<st di
o.h>
i
ntmai n()
{
i
ntv ar=5;
pri
nt f
("Value:%d\n"
,var
);
pri
nt f
("Address:%u",
&var)
;//
Not
ice,
theamper
sand(
&)bef
orev
ar.
return0;
}

Out
put

Val
ue:5
Addr
ess:2686778

Not
e:Youmayobt
aindi
ff
erentv
alueofaddr
esswhi
l
eusi
ngt
hiscode.

I
nabovesour
cecode,val
ue5isst
oredi
nthememor
ylocat
ion2686778.v
ari
sjustt
he
namegi
ventothatl
ocati
on.

Poi
nterv
ari
abl
es
I
nC, y
oucancreat
easpecialv
ariabl
ethatst
orest
headdress(
rat
hert
hant
hev
alue)
.
Thi
svari
abl
eiscal
ledpoi
ntervar
iabl
eorsimplyapoi
nter
.
Howt
ocr
eat
eapoi
nterv
ari
abl
e?

dat
a_t
ype*poi
nter
_var
iabl
e_name;
i
nt*p;

Abov
est
atementdef
i paspoi
nes, nterv
ari
abl
eoft
ypei
nt.

Ref
erenceoper
ator(
&)andDer
efer
enceoper
ator(
*)

Asdi
scussed,
&iscal
l
edr
efer
enceoper
ator
.Itgi
vesy
out
headdr
essofav
ari
abl
e.

Li
kewise,ther
eisanot
heroper
atort
hatget
syout
hev
aluef
rom t
headdr
ess,
iti
scal
l
ed
aderefer
enceoperat
or*.

Bel
owexampleclear
lydemonst
rat
est
heuseofpoi
nter
s,r
efer
enceoper
atorand
der
efer
enceoper
ator.

Note:The*si
gnwhendeclar
ingapoi
nteri
snotader
efer
enceoper
ator
.Iti
sjusta
si
mi l
arnot
ati
ont
hatcr
eatesapoint
er.

Exampl
e:HowPoi
nterWor
ks?

#i
ncl
ude<stdi
o.h>
i
ntmain(
)
{
i
nt*pc,c;

c=22;
pr
int
f("
Addr
essofc:%u\n"
,&c);
pr
int
f("
Val
ueofc:%d\n\
n",c)
;

pc=&c;
pr
int
f("
Addr
essofpoi
nterpc:%u\
n",pc);
pr
int
f("
Cont
entofpoi
nterpc:
%d\n\n",
*pc);

c=11;
pr
int
f("
Addr
essofpoi
nterpc:%u\
n",pc);
pr
int
f("
Cont
entofpoi
nterpc:
%d\n\n",
*pc);

*pc=2;
pri
ntf
("Addr
essofc:%u\n"
,&c);
pri
ntf
("Val
ueofc:%d\n\
n",c)
;
ret
urn0;
}
Out
put

Addr
essofc:2686784
Val
ueofc:22

Addr
essofpoi
nterpc:2686784
Cont
entofpoi
nterpc:
22

Addr
essofpoi
nterpc:2686784
Cont
entofpoi
nterpc:
11

Addr
essofc:2686784
Val
ueofc:2

Expl
anat
ionoft
hepr
ogr
am

1.i
nt*pc,
c;

Her e,apoi
nterpcandanor mal v
ari
ablec,bot
hoftypeint,
iscreat
ed.
Sincepcandcar enotini
ti
ali
zedatfi
rst
,poi erpcpoi
nt ntstoeit
hernoaddr
essor
ar andom address.And,v
ari
ablechasanaddr essbutcontai
nsa
random garbagev al
ue.

2.c=22;

Thi
sassigns22tot hevar
i ec,
abl i
.e.
,22isst
oredi
nthememor ylocat
ionof
var
i ec.
abl
Notethat,
whenprinti
ng&c(addr
essofc),weuse%uratherthan%dsinceaddr
ess
i
susuallyexpr
essedasanunsignedint
eger(al
waysposit
ive).

3.pc=&c;

Thi
sassi
gnst
headdr
essofv
ari ect
abl othepoi
nterpc.
Youseethev
alueofpci
ssameast essofcandt
headdr entofpci
hecont s22
aswell
.

4.c=11;

Thi
sassi
gns11tovari ec.
abl
Si
nce,
poi erpcpoi
nt ntstot essasc,
hesameaddr val
uepoi
ntedbypoi
nterpci
s
11aswel
l.

5.*pc=2;

Thischangethev al
ueatthememorylocat
ionpoi
ntedbypoi erpct
nt o2.
Sincetheaddressofthepoi erpci
nt ssameast headdressofc,v
alueofci
sal
so
changedto2.

Commonmi
stakeswhenwor
kingwi
thpoi
nter
s

Suppose,
youwantpoi
nterpct
opoi
ntt
ot essofc.Then,
headdr

i
ntc,
*pc;

//Wr
ong!pci
saddresswher
eas,
//ci
snotanaddr
ess.
pc=c;

/
/Wrong!*
pcistheval
uepoi
ntedbyaddr
esswher
eas,
/
/&cisanaddr
ess.
*
pc=&c;

//Cor
rect
!pci
sanaddressand,
//&ci
salsoanaddr
ess.
pc=&c;

/
/Corr
ect!*
pcistheval
uepoint
edbyaddr
essand,
/
/cisalsoaval
ue(notaddr
ess).
*
pc=c;
CPoi
nter
sandAr
ray
s

Beforeyoulearnabouthowpoi
nter
scanbeusedt
owor
kwi
thar
ray
s,besur
etocheck
thesetwotopics:

 CArr
ays
 CPoi
nter
s

Now,checkt
hissimplepr
ogr
am.Thi
spr
ogr
am pr
int
saddr
essofeachi
ndi
vi
dual
el
ementofanarray.

#i
ncl
ude<st
dio.
h>
i
ntmain(
)
{
i
ntx[
4];
i
nti
;

f
or(
i=0;i<4;++i
)
{
pr
int
f("
&x[
%d]=%u\
n",
i,&x[
i]
);
}

pr
int
f("
Addr
essofar
rayx:
%u"
,x)
;

ret
urn0;
}

Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbesomet
hingl
i
ke:

&x[
0]=1450734448
&x[
1]=1450734452
&x[
2]=1450734456
&x[
3]=1450734460
Addr
essofarr
ayx:1450734448

Thereisadif
ferenceof4byt
esbetweentwoconsecut
iveel
ement
sofar
rayx.I
tis
becausethesizeofinti
s4byt
es(onourcompi
ler)
.

Not
icet
hat
,pr
int
ing&x[
0]andxgav
eust
hesamer
esul
t.

Rel
ati
onbet
weenAr
ray
sandPoi
nter
s
Consi
deranar
ray
:

i
ntx[
4];

Fr
om theabov eexample,
it'
scl hatxand&x[
eart 0]bot
hcont
ainst
hesameaddr
ess.
Hence, 0]i
&x[ sequival
enttox.

And,
x[0]i
sequi
val
entt
o*x.

Si
mil
arl
y,

1]i
 &x[ sequiv
alenttox+1andx[1]i
sequi
v al
entto*( .
x+1)
2]i
 &x[ sequiv
alenttox+2andx[2]i
sequi
v al
entto*( .
x+2)
 ..
.
 Basical
ly,
&x[]i
i sequi
valentt
ox+iandx[
i]isequi
val
entto*(
x+i
).

Exampl
e1:
Poi
nter
sandAr
ray
s
#incl
ude<st di
o.h>
i
ntmai n()
{
i
nti,x[6]
,sum =0;
pri
ntf(
"Enter6number
s:"
);
for(
i=0; i<6;++i
)
{
scanf(
"%d",x+i
);

sum +=*(x+i
);
}
pri
ntf
("Sum =%d",sum)
;
ret
urn0;
}

Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

Ent
er6number
s:2
3
4
4
12
4
Sum =29
Inmostcontext
s,ar r
aynames" decays"t
opointer
s.I
nsimpl
ewor ds,ar
raynamesare
convert
edtopointers.That'
sthereasonwhyyoucanusepointerwitht
hesamename
asarraytomanipulateelementsofthearr
ay.However
,youshouldrememberthat
point
ersandarr
ay sarenotsame.

Exampl
e2:
Arr
aysandPoi
nter
s
#i
nclude<stdio.
h>
i
ntmai n(
)
{
i
ntx[5]={1,2,3,4,
5};
i
nt*ptr;

pt
r=&x[
2];

pr
int
f("
*pt
r=%d\n"
,*pt
r);
pr
int
f("
*pt
r+1=%d\n"
,*pt
r+1)
;
pr
int
f("
*pt
r-
1=%d",
*ptr
-1)
;

r
etur
n0;
}

Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

*
ptr=3
*
ptr+1=4
*
ptr-
1=2

I
nthisexample, 2](
&x[ addressoft
het
hir
delementofar
rayx)i
sassi
gnedt
othepoi
nter
pt
r.Hence,3wasdisplay
edwhenwepr i
nted*pt
r.

And,pri
nti
ng*pt
r+1gi
vesust
hef
our
thel
ement
.Si
mil
arl
y,pr
int
ing*pt
r1g
- i
vesust
he
secondelement.

CCal
lbyRef
erence:Usi
ngpoi
nter
s

Youcannotonlypassvar
iables/
val
uestoaf
uncti
on,butyoucanal
sopassaddr
esses
toafunct
ion.Af
teral
l
,addressisal
sosomekindofavalue.

Sincepoint
erstoreaddr
ess,y
oucanusepoi
ntert
oacceptt
hataddr
essi
nthef
unct
ion
defini
ti
on.Let
'stakeanexample:
Exampl
e:Passi
ngaddr
esst
oaFunct
ion

#incl
ude<stdi
o.h>
voidswap(
int*n1,i
nt*
n2)
;

i
ntmain()
{
i
ntnum1=5,
num2=10;

//addr
essofnum1andnum2i
spassed
swap(&num1,&num2)
;

pri
ntf
("num1=%d\
n",num1)
;
pri
ntf
("num2=%d"
,num2);
ret
urn0;
}

/
/point
ern1andn2storest
headdr
essofnum1andnum2r
espect
ivel
y
v
oidswap(int
*n1,
int
*n2)
{
i
ntt
emp;
t
emp=* n1;
*
n1=* n2;
*
n2=temp;
}

Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

num1=10
num2=5

headdressofnum1andnum2arepassedt
otheswap(
)funct
ionusi
ngswap(
&num1,
&num2)
;.Poi
nt sn1andn2st
er orest
hem.

Whent heval
ueatt essesn1andn2ar
headdr num1andnum2ar
echanged, ealso
changedrespecti
vely
.Thati
s,i
f*n1and*n2arechangedi
nsi
det
heswap(
)funct
ion,num1
andnum2ar ealsochangedinsi
dethemai )f
n( unct
ion.

I
nsidet
heswap(
)funct
ion,
*n1and*n2swapped.Hence,
val
uest
or nnum1andnum2
edi
ar
ealsoswapped.

Not
icet
hat
, )i
swap( snotr
etur
ningany
thi
ng;
it'
sret
urnt
ypei
svoi
d.

Thist
echniqueisknownascal
lbyref
erenceinCpr
ogrammi
ng.I
t'
sbecauseaddr
esses
arepassedtothefunct
ioni
nst
eadoftheactual
val
ue.
CDy
nami
cMemor
yAl
locat
ion

narr
ayisacoll
ect
ionoffi
xednumberofv
aluesofasi
ngl
ety
pe.Thati
s,y
ouneedt
o
decl
aret
hesizeofanarr
aybefor
eyoucanuseit
.

Sometimes,t
hesi
zeofarr
ayyoudeclar
edmaybeinsuf
fici
ent
.Tosol
vet
hisi
ssue,y
ou
canall
ocatememorymanual
lydur
ingrun-
ti
me.Thi
sisknownasdynami
cmemor y
al
locat
ioninCpr
ogramming.

Ther
eare4li
brar
yfuncti
onsdef
inedunder<stdl
i
b.h>ma kesdynami
cmemor
yal
l
ocat
ion
i
nCpr ogr
amming.Theyaremal
l
oc(,
)cal
l
oc(
),r
eall
oc()andfr
ee(
).

Cmal
l
oc(
)
Thename"
mal
l
oc"st
andsf
ormemor
yal
l
ocat
ion.

Themall )f
oc( uncti
onreserv
esablockofmemoryoft
hespecifi
ednumberofby
tes.And,
i
tret
urnsapointeroftypevoi
dwhi
chcanbecastedi
ntopoi
nterofanyf
orm.

Sy
ntaxofmal
l
oc(
)
pt
r=(
cast
-t
ype*
)mal
l
oc(
byt
e-si
ze)

Exampl
e:

pt
r=(
int
*)mal
l
oc(
100*si
zeof
(i
nt)
);

Consider
ingt
hesi
zeofi
nti
s4by t
es,
thi
sstatemental
locates400by
tesofmemor
y.And,
thepoi erpt
nt rhol
dst
headdressoft
hefi
rstbytei
ntheallocat
edmemory.

Howev
er,
ift
hespacei
sinsuf
fi
cient
,al
l
ocat
ionf
ail
sandr
etur
nsaNULLpoi
nter
.

Ccal
l
oc(
)
Thename"
cal
l
oc"st
andsf
orcont
iguousal
l
ocat
ion.

Themall )f
oc( unct
ional
l
ocat
esasingl
eblockofmemory
.Wher
eas,
cal
l )a
oc( l
locat
es
mult
ipl
eblocksofmemoryandi
niti
ali
zest
hem t
ozer
o.
Sy
ntaxofcal
l
oc(
)
pt
r=(
cast
-t
ype*
)cal
l
oc(
n,el
ement
-si
ze)
;

Exampl
e:

pt
r=(
fl
oat
*)cal
l
oc(
25,
sizeof
(fl
oat
));

Thi
sstat
emental
l
ocat
escont
iguousspacei
nmemor
yfor25el
ement
seachwi
tht
he
si
zeoffl .
oat

Cf
ree(
)
Dynamical
l
yall
ocat
edmemor ycreatedwit
heithercal
l )o
oc( rmal
l )d
oc( oesn'
tgetf
reedon
t
heirown.Youmustexpl
i
cit
lyusefr )t
ee( or
eleasethespace.

Sy
ntaxoff
ree(
)
f
ree(
ptr
);

Thi
sst
atementf
reest
hespaceal
l
ocat
edi
nthememor
ypoi
ntedbypt
r.

Exampl
e1:
mal
l
oc(
)andf
ree(
)

Thisprogr
am cal
culat
est hesum ofnnumbersenteredbyt
heuser
.Toper
for
mthis
task,
memor yisdynamicall
yall
ocatedusi
ngmal
loc(
),andmemoryi
sfr
eedusi
ngf
ree(
)
funct
ion.

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

i
ntmain()
{
i
ntn,i
,*pt
r,sum =0;

pri
ntf
("Ent
ernumberofel
ement
s:"
);
scanf
("%d",&n)
;

pt
r=(int
*)mal
l
oc(
n*si
zeof
(i
nt)
);
i
f(
ptr==NULL)
{
pri
ntf(
"Er
ror
!memor
ynotal
l
ocat
ed.
")
;
exi
t(0)
;
}

pri
ntf(
"Enterelement
s:"
);
for(
i=0; i
<n; ++i)
{
scanf(
"%d" ,
ptr+i)
;
sum +=* (pt
r+i);
}

print
f("
Sum =%d"
,sum)
;
free(
ptr)
;
retur
n0;
}

Exampl
e2:
cal
l
oc(
)andf
ree(
)

Thisprogram cal
culat hesum ofnnumber
est sent
eredbyt
heuser
.Toper
for
mthi
s
task,
call
oc()andf
r )i
ee( sused.

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

i
ntmai n()
{
i
ntn, i
,*pt
r,sum =0;
pri
ntf(
"Ent
ernumberofel
ement
s:"
);
scanf(
"%d",&n)
;

pt
r=( i
nt*
)call
oc(
n,si
zeof
(i
nt)
);
i
f(
pt r==NULL)
{
print
f("
Err
or!memorynotal
l
ocat
ed.
")
;
exit(
0);
}

pri
ntf(
"Enterelement
s:"
);
for(
i=0; i
<n; ++i)
{
scanf(
"%d" ,
ptr+i)
;
sum +=* (pt
r+i);
}

print
f("
Sum =%d"
,sum)
;
free(
ptr)
;
retur
n0;
}
Cr
eal
l
oc(
)
Ift
hedynami
cal
l
yall
ocatedmemoryisi
nsuf
fi
cientormorethanrequir
ed,
youcan
changet
hesi
zeofpr
eviousl
yal
l
ocatedmemoryusingreal
l )f
oc( uncti
on

Sy
ntaxofr
eal
l
oc(
)
pt
r=r
eal
l
oc(
ptr
,x)
;

Her
e,pt
risr
eal
l
ocat
edwi
t zex.
hnewsi

Exampl
e3:
real
l
oc(
)
#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
dli
b.h>

i
ntmai n()
{
i
nt*ptr,i,
n1, n2;
pri
ntf(
"Entersizeofar
ray
:")
;
scanf(
"%d" ,
&n1) ;

pt
r=(
int
*)mal
l
oc(
n1*si
zeof
(i
nt)
);

pri
ntf
("Addressesofprev
iousl
yal
l
ocat
edmemor
y:"
);
for
(i=0;i<n1; ++i)
pri
ntf("
%u\ n"
,pt
r+i)
;

pri
ntf
("\nEnt
ernewsizeofarr
ay:")
;
scanf
("%d",&n2);
ptr=reall
oc(pt
r,n2*si
zeof
(i
nt))
;

pri
ntf
("Addressesofnewlyal
l
ocat
edmemor
y:"
);
for
(i=0;i<n2; ++i
)
pri
ntf("
%u\ n"
,pt
r+i);
ret
urn0;
}

Wheny
our
unt
hepr
ogr
am,
theout
putwi
l
lbe:

Entersi
zeofarr
ay:
2
Addressesofpr
evi
ousl
yal
l
ocat
edmemor
y:26855472
26855476

Ent
ernewsizeofarr
ay:4
Addr
essesofnewlyal
locat
edmemor
y:26855472
26855476
26855480
26855484

C-Poi
ntert
oPoi
nter

Apoi nt
ert oapoint eri
saf or
m ofmulti
plei
ndir
ect
ion,orachai
nofpoint
ers.Normall
y,a
point
ercont ai
nst headdressofav ar
iabl
e.Whenwedef ineapoi
ntert
oapoi nt
er,
the
fi
rstpointercontainstheaddressofthesecondpoint
er,whi
chpoi
ntstothelocat
ion
thatcontainstheact ualv
alueasshownbel ow.

Av ari
abl
ethati
sapoint
ertoapoi nt
ermustbedeclaredassuch.Thisi
sdoneby
pl
acinganaddit
ional
ast
er i
skinfr
ontofitsname.Forexampl
e,thefoll
owi
ng
declar
ati
ondecl
aresapointert
oapoi nt
eroftypei
nt−

i
nt*
*var
;

Whenat ar
getv
alueisi
ndi
rect
lypoi
ntedtobyapoint
ertoapoi
nter
,accessi
ngthat
val
uerequi
rest
hattheast
eri
skoper
atorbeappl
iedtwice,
asi
sshownbel owint
he
example−

Li
veDemo
#i
ncl
ude<st
dio.
h>

i
ntmai
n(){

i
ntv
ar;
i
nt*
ptr
;
i
nt*
*ppt
r;

v
ar=3000;

/*taket
headdr
essofv
ar*
/
ptr=&var;

/*t
aket
headdr
essofpt
rusi
ngaddr
essofoper
ator&*
/
ppt
r=&ptr
;

/*taketheval
ueusingpptr*/
pri
ntf(
"Val
ueofvar=%d\ n",var)
;
pri
ntf(
"Val
ueavai
lableat*ptr=%d\n"
,*pt
r);
pri
ntf(
"Val
ueavai
lableat**pptr=%d\
n",*
*pptr
);

ret
urn0;
}
Whent
heabov
ecodei
scompi
l
edandexecut
ed,
itpr
oducest
hef
oll
owi
ngr
esul
t−

Val
ueofvar=3000
Val
ueavai
labl
eat*
ptr=3000
Val
ueavai
labl
eat*
*pptr=3000

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy