4/30/12

Pointers

Subsections What is a Pointer? Pointer and Functions Pointers and Arrays Arrays of Pointers Multidimensional arrays and pointers Static Initialisation of Pointer Arrays Pointers and Structures Common Pointer Pitfalls Not assigning a pointer to memory address before using it Illegal indirection Exercise

Pointers
Pointer are a fundamental part of C. If you cannot use pointers properly then you have basically lost all the power and flexibility that C allows. The secret to C is in its use of pointers. C uses pointers a lot. Why?: It is the only way to express some computations. It produces compact and efficient code. It provides a very powerful tool. C uses pointers explicitly with: Arrays, Structures, Functions. NOTE: Pointers are perhaps the most difficult part of C to understand. C's implementation is slightly different DIFFERENT from other languages.

What is a Pointer?
A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type. The unary or monadic operator & gives the ``address of a variable''. The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''. To declare a pointer to a variable do:
it*one; n pitr

NOTE: We must associate a pointer to a particular type: You can't assign the address of a short int to a long int, for instance. Consider the effect of the following code:
www.cs.cf.ac.uk/Dave/C/node10.html 1/10

x=i. Assume for the sake of this discussion that variable x rsdsa mmr lcto 10 ya 20adi a 10. Consider Fig. t s h ntr o tepitr vleta i nw aue f h ones au ht s e.wihi 1 h aus f .Nt Apitri eie t eoy oain 0. Nx ygt asge t tecnet o i. o . one. i =&.cf.1. .hc s . o es sind o tevle o x.cs.Tu i i pretylgl(lhuhntalta cmo) ifrn ye hs t s efcl ea atog o l ht omn t asg tecretvleo i t x Tevleo i a ti isati o sin h urn au f p o .S i gt one o n nee n s sind o h drs f &) o p es lae wt tevle10 odd ih h au 0. It is worth considering what is going on at the machine level in memory to fully understand how pointer work. 9.ac. h au f p t hs ntn s 10 0. Fnlyw cnasg avlet tecnet o apitr(i) ial e a sin au o h otns f one *p. Fg 91Pitr VralsadMmr Nwteasgmnsx=1ady=2 i. www.Yums MOTN: hn one s elrd t os o on nwee o ut sti t pitsmweebfr yuuei. t 0 n p t 00 oe one s avral adtu isvle ne t b soe smwee I i te aibe n hs t aus ed o e trd oehr. .4/30/12 Pointers itx=1 y=2 n .html 2/10 . IPRAT We apitri dcae i de ntpitayhr.uk/Dave/C/node10. it*p n i.. W hv arayse ta Ci nttofsyaotasgigvle o e ae led en ht s o o us bu sinn aus f dfeettp.h oain f .telcto o x S ygt asge t ons o eoy oain 0 . aibe n eoy o h sinet n ovosyla teevle it tevrals i i dcae t b a biul od hs aus no h aibe. p *p=3 i . it*p n i. p s elrd o e pitrt a itgradi asge t teadeso x(x.I ti eapei crety et es sind o h otns f p n hs xml p urnl pit t mmr lcto 10. e t o on oehr eoe o s t S . p x y=*p i.

.4/30/12 Pointers *p=10 i 0.ac. one s eiiey O n nee. fp fp 0 +*l. nepn h mlmnain f hs Tebs wyt suyti i t lo a a eapeweew ms b al h et a o td hs s o ok t n xml hr e ut e be t rciecagdprmtr. nrmn h one +l) t oe o h oiin hw ye n I o teohrhn w add2t tepitrte i mvs2fot f n h te ad e de o h one hn t oe la pstosie8btsa soni teFgr. +fp (fp+. We Cpse agmnst fntosi pse te b vle hn ass ruet o ucin t ass hm y au.Ohrlnugsms tefc ta pitr as xlcty o o hs te agae ak h at ht ones lo udri teipeetto o ti. ucin n eev h e au ak ne o ucin a iihd Ohrlnugsd ti (. la fp fq *l =*l +1. Teeaemn csswe w mywn t atrapse agmn i te hr r ay ae hn e a at o le asd ruet n h fnto adrcietenwvlebc oc t fnto hsfnse.html 3/10 . ye s hw n h iue PitradFntos one n ucin Ltu nweaietecoerltosi btenpitr adCsohr e s o xmn h ls eainhp ewe ones n ' te mjrprs W wl satwt fntos ao at. i =&. wl gnrt a err(rga cah!. *l)+ fq=fp l l..cf. . h one y n `lc' eoy S fracaatrpitr+c_t ad 1bt t teades o o hrce one +hpr ds ye o h drs. e il tr ih ucin. Cnie afotvral (l adapitrt afot(l)a soni osdr la aibe f) n one o la fp s hw n Fg 92 i. NT:Apitrt ayvral tp i a adesi mmr .wihi OE one o n aibe ye s n drs n eoy . oiin . W cnd itgraihei o apitr e a o nee rtmtc n one: fot*l. one rtmtc sue ht l ons o l hn f e iceettepitr(+fp i mvst tepsto son4btso. ss ones epiil t d ti.vrprmtr i PSA) Cue pitr te agae o hs eg a aaees n ACL. Fg 92PitrAihei Asm ta fppit t f te i w i. p x *p=10 i 0.hc s a itgrades Apitri dfntl NTa itgr n nee drs. Fra itgro fot+i o +fpad 4btst teades o n nee r la +p r +l ds ye o h drs.We w iceetapitrw ices ay ye h aa s trd n hn e nrmn one e nrae tepitrb oe`bok'mmr. o eev hne aaees Ltu tyadwieafnto t sa vralsaon? e s r n rt ucin o wp aibe rud Teuulfnto cl: h sa ucin al www.cs. Terao w ascaeapitrt adt tp i s ta i koshw h esn e soit one o aa ye s o ht t nw o mn btstedt i soe i.uk/Dave/C/node10.*l. il eeae n ro porm rs!) Tecretuei: h orc s s it*p n i. . itx n .

ucin n ces drs f ucin Tu orfnto cl i orpormwudlo lk ti: hs u ucin al n u rga ol ok ie hs sa(a &) wp&.4/30/12 Pointers sa(..uk/Dave/C/node10.) { CODp OR .. eun p / rtr adeso p* * eun drs f / } Hr w rtr apitrwoecnet aeimdaeyuwapdit a ee e eun one hs otns r meitl nrpe no vral. p =*or_n. *y=tm. ..ac.. } COD*or_n. n ep tm =*x ep p. t il o ae en vrrte srih atrtefnto h suttog s ti i pretysf. . .. 4/10 .. b TeCd t sa i fil srihfrad h oe o wp s ary tagtowr: vi sa(n *x it*y od wpit p. n p) {ittm. tagt fe h ucin a qi huh o hs s efcl ae Pitr adAry ones n ras Pitr adary aevr coeylne i C ones n ras r ey lsl ikd n . Cnie tefloig osdr h olwn: ita1] x n [0.cs... 1 codf(. ..html it*a n p. Hn:tiko aryeeet arne i cneuiemmr lctos it hn f ra lmns ragd n osctv eoy oain.Ti masta teades oa o ucin ht a o iihd hs en ht h drs saei fe adcnb oewitn I wl nthv be oewitn pc s re n a e vrrte. www. mi( an) { CODp..eg: ak tutrs .W ms d ti srih aa a tevral w pitdt ws aibe e ut o hs tagt wy s h aibe e one o a lclt afnto ta hsnwfnse. / cnet o pitr* * otns f one / *x=*y p p.. tpdfsrc {la xyz}COD yee tut fot . / dcaef t rtr pro * elr n o eun t f CODtp * OR ye / .. p ep } W cnrtr pitrfo fntos Acmo eapei we psig e a eun one rm ucin.. p=. OR..*or_n) OR 1 codf(..) / asg cnet o adesrtre * * sin otns f drs eund / . O' OK Pitr poieteslto:Ps teadeso tevralst te ones rvd h ouin as h drs f h aibe o h fntosadacs adeso fnto.b wpa ) WNTWR.cf. / asg srcuevle * * sin tutr aus / rtr &.. OR codf(. omn xml s hn asn bc srcue. . .

[] a e rte s ( ) ie &[] .4/30/12 Pointers p =&[] / p pitrt adeso a0 * a a0. oee s uh oe ute n t ik ewe ras n ones Freapew cnjs tp o xml e a ut ye p =a a .cs. isedo nta f p =&[] a a0 ad n ai cnb witna *a+i.ac. We a aryi pse t afnto wa i atal pse i is hn n ra s asd o ucin ht s culy asd s t iiileeet lcto i mmr. wie(p! ` hl * = www. W as epespitradesn lk ti: e lo xrs one drsig ie hs p[] ai *p +i. / x=cnet o p ([]i ti cs)* * otns f a a0 n hs ae / Fg 93Ary adPitr i. o oe f hs W cnnwudrtn hwary aepse t fntos e a o nesad o ras r asd o ucin. n tlnca [) A euvln dcaaini :itsre(hr*) n qiaet elrto s n tlnca s. ae ue o nesad t e il e ltmr o ti. Ti sufi vr iprat Mk sr yuudrtn i. ai a+i . hr s sre( i asadr lbayfnto (hpe 1)ta rtrste tln) s tnad irr ucin Catr 8 ht eun h lnt o asrn.. sneca s] ic hr [ ca *.cf.93 uigapitrw cudd: o e oehr n h ra Fg . * a one o drs f [] / x=*a p. ras n ones T gtsmweei teary(i.W cnd one s aibe e a o p =aadp+.W wl sea hs tf s ey motn. 5/10 . nta lmns oain n eoy S: o sre() tlns sre(s0) tln&[] Ti i wyw dcaetefnto: hs s h e elr h ucin itsre(hrs].uk/Dave/C/node10.Ltslo a hww mywieafnto: egh f tig e' ok t o e a rt ucin itsre(hr*) n tlnca s {ca * =s hr p . .) sn one e ol o p +i a ai [] WRIG Teei n budcekn o ary adpitr s yucn ANN: hr s o on hcig f ras n ones o o a esl g byn arymmr adoewieohrtig.a=p ada+AEILGL n ra s o aibe a n + R LEA. (a ) Hwvrpitr adary aedfeet oee ones n ras r ifrn: Apitri avral. aiy o eod ra eoy n vrrt te hns Chwvri mc mr sbl i isln btenary adpitr. a n a+ A Aryi ntavral.html ) .

Ary o Pitr ras f ones W cnhv ary o pitr snepitr aevrals e a ae ras f ones ic ones r aibe. tr ie n-oed n n i hr ra Fg . Eapeue xml s: Sr lnso tx o dfeetlnt. Hwcnw d ti? o a e o hs: Soelnsedt-n i oebgca ary(i.4/30/12 Pointers } p+ +. ras f ones Srn otn xml) Ti eiiae: hs lmnts cmlctdsoaemngmn. Ti ue pitr adasgmn b vle hs ss ones n sinet y au. opiae trg aaeet hg oehaso mvn lns ih vred f oig ie.srp( i o es rt ucin o oy tig o nte tig tcy) s asadr lbayfnto ta de ti. tnad irr ucin ht os hs vi srp(hr*. Fg 94Ary o Pitr (tigSrigEape i. opr w ie sn tcp) tnad irr ucin I 2lnsaeoto odr.html 6/10 .ca *) od tcyca s hr t { wie((s+=*+)! ` hl *+ t+ = )} . rtr ps eun -.wp one n one ra nt tx) et. Mliiesoa ary adpitr utdmninl ras n ones W sol tiko mliiesoa ary i adfeetwyi C e hud hn f utdmninl ras n ifrn a n : www.94.uk/Dave/C/node10. . Vr Na! ey et! NT:Ue o Nl saeet wt wie OE ss f ul ttmns ih hl.cs. Ary o Pitr aeadt rpeetto ta wl cp efcety ras f ones r aa ersnain ht il oe fiinl adcneinl wt vral lnt tx lns n ovnety ih aibe egh et ie.sa pitri pitrary(o f ie r u f re .) nwl il dlmtlns eii ie. ot ie f et f ifrn egh NT:Tx cntb mvdo cmae i asnl oeain OE et a' e oe r oprd n ige prto. Soepitr i adfeetaryweeec pitrpit t 1t tr ones n ifrn ra hr ah one ons o s ca o ec nwln. Nwlt wieafnto t cp asrn t aohrsrn. hr f ah e ie Cmaetolnsuigsrm( sadr lbayfnto.cf.ac.

. . n *)3] elrs one o n ra f 5 ns it*[5.} `e'. n eoy nm hs1 pitreeet. Teavnaeo telte i ta ec pitrcnpitt ary b o h datg f h atr s ht ah one a on o ras e f dfeetlnt... `fb' .h ubr f os s reeat Terao frti i pitr aan Cnest ko hwmn clmsi h esn o hs s ones gi.. o es ok t h sbl) ifrne ewe ones n ras Srnsaeacmo apiaino ti. `a'.. o ee: r vn fit(a[5){. `fb' .uk/Dave/C/node10. `a'..} `e'.dcae apitrt a aryo 3 it. n a3] elrs n ra f 5 ones o ns Nwlt lo a te(ute dfeec btenpitr adary. tig r omn plcto f hs Cnie: osdr ca *ae1] hr nm[0. ed o nw o ay oun n odrta i cnjm fo rwt rwi mmr..} (n [[5) . . oun . .cs. We w ps a2 aryt afnto w ms seiytenme o hn e as D ra o ucin e ut pcf h ubr f clms. www. Hwvr oee Aaei atu 20eeet2 ca ary nm s re 0 lmn D hr ra. W ne prnhss(a sne[ hv ahge peeec ta * e ed aetei *) ic ] ae ihr rcdne hn S: o it(a[5. ifrn egh Cnie: osdr ca *ae]={`n mnh' `jn' hr nm[ `o ot'. W cnlglyd nm[]4 adAae3[]i C e a eal o ae3[] n nm[]4 n .4/30/12 Pointers A2 aryi ral a1 ary ec o woeeeet i isl a ary D ra s ely D ra. ca Aae1]2] hr nm[0[0.} (n *)3] . ah f hs lmns s tef n ra Hne ec an[]ntto.html 7/10 . acs eeet va ces lmns i 2*o +cl+bs_drs 0rw o aeades i mmr. ca Aae]1]={`n mnh' `jn' hr nm[[5 `o ot'.cf.tenme o rw i irlvn. []m oain Aryeeet aesoe rwb rw ra lmns r trd o y o. ae a 0 one lmns NT:I ec pitri nm i stt pitt a2 eeetaryte OE f ah one n ae s e o on o 0 lmn ra hn adol te wl 20casb staie( 1 eeet) n ny hn il 0 hr e e sd + 0 lmns.dcae a aryo 3 pitr t it...ac. re ht t a up rm o o o n eoy Cnieita5[5 t b pse i afnto: osdrn []3] o e asd n ucin W cnd: e a o fita]3] {.

. * sin one o t / te h oeao lt u acs amme o tesrcuepitdt b a prtr es s ces ebr f h tutr one o y pitrie: one.html 8/10 ..uk/Dave/C/node10. p_t tpr p_t tpr x=10 . ..ac. 2 Ary adAry o Pitr D ras n ras f ones Sai Iiilsto o Pitr ttc ntaiain f one Ary ras Iiilsto o ary o pitr i a ielapiainfra ntaiain f ras f ones s n da plcto o n itra sai ary nenl ttc ra.} } sai rsre apiaepraetbto mmr. osdr h floig olwn: src COD{la xyz}p.. `e'. Eape Lne Lss xml: ikd it www. p_t =&t / asgspitrt p * tpr p. tut OR fot .cs. y=p_t tpr y-30 .. . ttc eevs rvt emnn i f eoy Pitr adSrcue ones n tutrs Teeaefil srih fradadaeesl dfnd Cnie te hs r ary tagt owr n r aiy eie.4/30/12 Pointers Fg i.. `jn' `fb' `a'..cf. sm_n) oef( {sai ca *ots={`n mnh' ttc hr mnh `o ot'.. t src COD*tpr tut OR p_t.

) e il ok t hs mte frhri tenx Catr atr ute n h et hpe. Cmo PitrPtal omn one ifls Hr w wl hglgttocmo msae md wt pitr.html 9/10 / rqet10btso mmr * * eus 0 ye f eoy / . Teei msaeaoe Wa i i? hr s itk bv. LnigToNdsNT:W cnol dcaenx a apitrt ikn w oe OE e a ny elr et s one o EEET W cno hv aeeeto tevral tp a ti wudst LMN. ht s t N *i o n * =(hr* mlo(0) p ca ) alc10. EEET*et LMN nx. lo ol oe adm adesa iiilsto. * =`' p y. EEETn. ee e il ihih w omn itks ae ih ones Ntasgigapitrt mmr adesbfr o sinn one o eoy drs eoe uigi sn t it*. e s ae one: hr p Cnie: osdr * =(hr* mlo(0) p ca ) alc10. drs t ntaiain Ilglidrcin lea nieto Spoew hv afnto mlo( wihtist alct mmr ups e ae ucin alc) hc re o loae eoy dnmcly(trntm)adrtrsapitrt boko mmr yaial a u ie n eun one o lc f eoy rqetdi scesu o aNL pitr euse f ucsfl r UL one ohrie tews.N CMIE ERR As xcudsm rno hs a e ad o pt O OPLR RO. hr mlo( tnad irr ucin se ae) Ltu hv apitr ca *.n. }EEET LMN. www. x=&.96 w wl lo a ti h bv oe ik oe 1 o 2 Fg .cs. Ti myb hr t so. LMN 1 2 n. y * =10 x 0.cf.et=&2 1nx n. e r loe o e pitrrfrnesne4btsaestaiefraypitr one eeec ic ye r e sd o n one.ac.uk/Dave/C/node10. e ant ae lmn f h aibe ye s hs ol e u arcriedfnto wihi NTALWD W aealwdt sta p eusv eiiin hc s O LOE. n x * =10 x 0.4/30/12 Pointers tpdfsrc { itvle yee tut n au.asadr lbayfnto (e ltr. Fg i. ca *alc). Teaoecd lnsand n t n (i. w ne apyia lcto sy ity e ed hscl oain a: n .

f oe etfe n rbe s f o eoy s vial n s UL Teeoew cntd: hrfr e a' o * =`'.asot rt rga o id h ubr f ie ht ie odie hr srn)ocr i asnec (..b b i a sprt rt rga ht ae he aibe a .uk/Dave/C/node10. hrce. ) n s eaae prmtr adrttstevle soe s ta vleage t b. Eecs 144 xrie 25 Wieapormt fn tenme o tmsta agvnwr(. Eecs xrie Eecs 143 xrie 25 WieaCpormt ra truha aryo aytp uigpitr. * =`' p y. ') ei() xt1. Tesnec i "h ctsto temt. o cadct a n o . tig cus n etne ie og tig) Ra dt fo sadr ipt Tefrtln i asnl wr. p y. I cd rciidoepolmi i n mmr i aalbeadpi NL.ac.. Ago Cpormwudcekfrti: od rga ol hc o hs p=(hr* mlo(0) ca ) alc10. i (p= NL) f = UL {pit(`ro:Oto Mmr rnf`Err u f eoy } n'.cf. Eecs 145 xrie 25 Wieapormta tkstrevral (. Dv Mrhl ae asal 1519 //99 www. Tecretcd sol b: h orc oe hud e p=(hr* mlo(0) ca ) alc10. lo os o on o n drs.Ra bt u t anwie olwd y eea et n h eod ie ed oh p o eln caatr adisr atriaignl bfr poesn.html 10/10 .wihi ed aa rm tnad nu.b t aaees n oae h aus trd o ht au os o e . rt rga o ed hog n ra f n ye sn ones WieaCpormt sa truhti aryt fn apriua vle rt rga o cn hog hs ra o id atclr au.cs. h etne s te a a n h a" Tewr ocr 2tms h od cus ie. n net emntn ul eoe rcsig Tpclotu sol b: yia upt hud e Tewr i "h" h od s te.aln srn!. h is ie s ige od hc s floe b gnrltx o tescn ln.4/30/12 Pointers Mlo rtrsapitr As pde ntpitt ayades alc eun one.