Professional Documents
Culture Documents
PointersC++Tutorials
Search:
Tutorials
Go
C++Language
Loggedinas:shyjuu
Pointers
Account
logout
C++
Information
Tutorials
Reference
Articles
Forum
Tutorials
C++Language
AsciiCodes
BooleanOperations
NumericalBases
C++Language
Introduction:
Compilers
BasicsofC++:
Structureofaprogram
Variablesandtypes
Constants
Operators
BasicInput/Output
Programstructure:
Statementsandflowcontrol
Functions
Overloadsandtemplates
Namevisibility
Compounddatatypes:
Arrays
Charactersequences
Pointers
Dynamicmemory
Datastructures
Otherdatatypes
Classes:
Classes(I)
Classes(II)
Specialmembers
Friendshipandinheritance
Polymorphism
Otherlanguagefeatures:
Typeconversions
Exceptions
Preprocessordirectives
Standardlibrary:
Input/outputwithfiles
FreeFullBookDownloads
Pointers
Inearlierchapters,variableshavebeenexplainedaslocationsinthecomputer'smemorywhichcanbeaccessedbytheir
identifier(theirname).Thisway,theprogramdoesnotneedtocareaboutthephysicaladdressofthedatainmemoryit
simplyusestheidentifierwheneveritneedstorefertothevariable.
ForaC++program,thememoryofacomputerislikeasuccessionofmemorycells,eachonebyteinsize,andeachwith
auniqueaddress.Thesesinglebytememorycellsareorderedinawaythatallowsdatarepresentationslargerthanone
bytetooccupymemorycellsthathaveconsecutiveaddresses.
Thisway,eachcellcanbeeasilylocatedinthememorybymeansofitsuniqueaddress.Forexample,thememorycell
withtheaddress1776alwaysfollowsimmediatelyafterthecellwithaddress1775andprecedestheonewith1777,andis
exactlyonethousandcellsafter776andexactlyonethousandcellsbefore2776.
Whenavariableisdeclared,thememoryneededtostoreitsvalueisassignedaspecificlocationinmemory(itsmemory
address).Generally,C++programsdonotactivelydecidetheexactmemoryaddresseswhereitsvariablesarestored.
Fortunately,thattaskislefttotheenvironmentwheretheprogramisrungenerally,anoperatingsystemthatdecides
theparticularmemorylocationsonruntime.However,itmaybeusefulforaprogramtobeabletoobtaintheaddressofa
variableduringruntimeinordertoaccessdatacellsthatareatacertainpositionrelativetoit.
Addressofoperator(&)
Theaddressofavariablecanbeobtainedbyprecedingthenameofavariablewithanampersandsign(&),knownas
addressofoperator.Forexample:
foo=&myvar;
Thiswouldassigntheaddressofvariablemyvartofoobyprecedingthenameofthevariablemyvarwiththeaddressof
operator(&),wearenolongerassigningthecontentofthevariableitselftofoo,butitsaddress.
Theactualaddressofavariableinmemorycannotbeknownbeforeruntime,butlet'sassume,inordertohelpclarify
someconcepts,thatmyvarisplacedduringruntimeinthememoryaddress1776.
Inthiscase,considerthefollowingcodefragment:
1 myvar=25;
2 foo=&myvar;
3 bar=myvar;
Thevaluescontainedineachvariableaftertheexecutionofthisareshowninthefollowingdiagram:
ReadFrom1MillionFreeTitlesDownload
TodayforFreeeBooks!
First,wehaveassignedthevalue25tomyvar(avariablewhoseaddressinmemoryweassumedtobe1776).
Thesecondstatementassignsfootheaddressofmyvar,whichwehaveassumedtobe1776.
Finally,thethirdstatement,assignsthevaluecontainedinmyvartobar.Thisisastandardassignmentoperation,as
alreadydonemanytimesinearlierchapters.
Themaindifferencebetweenthesecondandthirdstatementsistheappearanceoftheaddressofoperator(&).
Thevariablethatstorestheaddressofanothervariable(likefoointhepreviousexample)iswhatinC++iscalleda
pointer.Pointersareaverypowerfulfeatureofthelanguagethathasmanyusesinlowerlevelprogramming.Abitlater,
wewillseehowtodeclareandusepointers.
Dereferenceoperator(*)
Asjustseen,avariablewhichstorestheaddressofanothervariableiscalledapointer.Pointersaresaidto"pointto"the
variablewhoseaddresstheystore.
Aninterestingpropertyofpointersisthattheycanbeusedtoaccessthevariabletheypointtodirectly.Thisisdoneby
precedingthepointernamewiththedereferenceoperator(*).Theoperatoritselfcanbereadas"valuepointedtoby".
Therefore,followingwiththevaluesofthepreviousexample,thefollowingstatement:
baz=*foo;
Thiscouldbereadas:"bazequaltovaluepointedtobyfoo",andthestatementwouldactuallyassignthevalue25to
baz,sincefoois1776,andthevaluepointedtoby1776(followingtheexampleabove)wouldbe25.
http://www.cplusplus.com/doc/tutorial/pointers/
1/8
4/21/2015
PointersC++Tutorials
Itisimportanttoclearlydifferentiatethatfooreferstothevalue1776,while*foo(withanasterisk*precedingthe
identifier)referstothevaluestoredataddress1776,whichinthiscaseis25.Noticethedifferenceofincludingornot
includingthedereferenceoperator(Ihaveaddedanexplanatorycommentofhoweachofthesetwoexpressionscouldbe
read):
1 baz=foo;//bazequaltofoo(1776)
2 baz=*foo;//bazequaltovaluepointedtobyfoo(25)
Thereferenceanddereferenceoperatorsarethuscomplementary:
&istheaddressofoperator,andcanbereadsimplyas"addressof"
*isthedereferenceoperator,andcanbereadas"valuepointedtoby"
Thus,theyhavesortofoppositemeanings:Anaddressobtainedwith&canbedereferencedwith*.
Earlier,weperformedthefollowingtwoassignmentoperations:
1 myvar=25;
2 foo=&myvar;
Rightafterthesetwostatements,allofthefollowingexpressionswouldgivetrueasresult:
1
2
3
4
myvar==25
&myvar==1776
foo==1776
*foo==25
Thefirstexpressionisquiteclear,consideringthattheassignmentoperationperformedonmyvarwasmyvar=25.The
secondoneusestheaddressofoperator(&),whichreturnstheaddressofmyvar,whichweassumedittohaveavalueof
1776.Thethirdoneissomewhatobvious,sincethesecondexpressionwastrueandtheassignmentoperationperformed
onfoowasfoo=&myvar.Thefourthexpressionusesthedereferenceoperator(*)thatcanbereadas"valuepointedto
by",andthevaluepointedtobyfooisindeed25.
So,afterallthat,youmayalsoinferthatforaslongastheaddresspointedbyfooremainsunchanged,thefollowing
expressionwillalsobetrue:
*foo==myvar
Declaringpointers
Duetotheabilityofapointertodirectlyrefertothevaluethatitpointsto,apointerhasdifferentpropertieswhenit
pointstoacharthanwhenitpointstoanintorafloat.Oncedereferenced,thetypeneedstobeknown.Andforthat,
thedeclarationofapointerneedstoincludethedatatypethepointerisgoingtopointto.
Thedeclarationofpointersfollowsthissyntax:
type*name;
wheretypeisthedatatypepointedtobythepointer.Thistypeisnotthetypeofthepointeritself,butthetypeofthe
datathepointerpointsto.Forexample:
1 int*number;
2 char*character;
3 double*decimals;
Thesearethreedeclarationsofpointers.Eachoneisintendedtopointtoadifferentdatatype,but,infact,allofthemare
pointersandallofthemarelikelygoingtooccupythesameamountofspaceinmemory(thesizeinmemoryofapointer
dependsontheplatformwheretheprogramruns).Nevertheless,thedatatowhichtheypointtodonotoccupythesame
amountofspacenorareofthesametype:thefirstonepointstoanint,thesecondonetoachar,andthelastonetoa
double.Therefore,althoughthesethreeexamplevariablesareallofthempointers,theyactuallyhavedifferenttypes:
int*,char*,anddouble*respectively,dependingonthetypetheypointto.
Notethattheasterisk(*)usedwhendeclaringapointeronlymeansthatitisapointer(itispartofitstypecompound
specifier),andshouldnotbeconfusedwiththedereferenceoperatorseenabitearlier,butwhichisalsowrittenwithan
asterisk(*).Theyaresimplytwodifferentthingsrepresentedwiththesamesign.
Let'sseeanexampleonpointers:
1
2
3
4
5
6
7
8
//myfirstpointer
#include<iostream>
usingnamespacestd;
firstvalueis10
secondvalueis20
Edit
intmain()
{
intfirstvalue,secondvalue;
int*mypointer;
http://www.cplusplus.com/doc/tutorial/pointers/
2/8
4/21/2015
PointersC++Tutorials
9
10
11
12
13
14
15
16
17
mypointer=&firstvalue;
*mypointer=10;
mypointer=&secondvalue;
*mypointer=20;
cout<<"firstvalueis"<<firstvalue<<'\n';
cout<<"secondvalueis"<<secondvalue<<'\n';
return0;
}
Noticethateventhoughneitherfirstvaluenorsecondvaluearedirectlysetanyvalueintheprogram,bothendupwith
avaluesetindirectlythroughtheuseofmypointer.Thisishowithappens:
First,mypointerisassignedtheaddressoffirstvalueusingtheaddressofoperator(&).Then,thevaluepointedtoby
mypointerisassignedavalueof10.Because,atthismoment,mypointerispointingtothememorylocationof
firstvalue,thisinfactmodifiesthevalueoffirstvalue.
Inordertodemonstratethatapointermaypointtodifferentvariablesduringitslifetimeinaprogram,theexample
repeatstheprocesswithsecondvalueandthatsamepointer,mypointer.
Hereisanexamplealittlebitmoreelaborated:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//morepointers
#include<iostream>
usingnamespacestd;
firstvalueis10
secondvalueis20
Edit
intmain()
{
intfirstvalue=5,secondvalue=15;
int*p1,*p2;
p1=&firstvalue;//p1=addressoffirstvalue
p2=&secondvalue;//p2=addressofsecondvalue
*p1=10;//valuepointedtobyp1=10
*p2=*p1;//valuepointedtobyp2=valuepointedbyp1
p1=p2;//p1=p2(valueofpointeriscopied)
*p1=20;//valuepointedbyp1=20
cout<<"firstvalueis"<<firstvalue<<'\n';
cout<<"secondvalueis"<<secondvalue<<'\n';
return0;
}
Eachassignmentoperationincludesacommentonhoweachlinecouldberead:i.e.,replacingampersands(&)by
"addressof",andasterisks(*)by"valuepointedtoby".
Noticethatthereareexpressionswithpointersp1andp2,bothwithandwithoutthedereferenceoperator(*).The
meaningofanexpressionusingthedereferenceoperator(*)isverydifferentfromonethatdoesnot.Whenthisoperator
precedesthepointername,theexpressionreferstothevaluebeingpointed,whilewhenapointernameappearswithout
thisoperator,itreferstothevalueofthepointeritself(i.e.,theaddressofwhatthepointerispointingto).
Anotherthingthatmaycallyourattentionistheline:
int*p1,*p2;
Thisdeclaresthetwopointersusedinthepreviousexample.Butnoticethatthereisanasterisk(*)foreachpointer,in
orderforbothtohavetypeint*(pointertoint).Thisisrequiredduetotheprecedencerules.Notethatif,instead,the
codewas:
int*p1,p2;
p1wouldindeedbeoftypeint*,butp2wouldbeoftypeint.Spacesdonotmatteratallforthispurpose.Butanyway,
simplyrememberingtoputoneasteriskperpointerisenoughformostpointerusersinterestedindeclaringmultiple
pointersperstatement.Orevenbetter:useadifferentstatemetforeachvariable.
Pointersandarrays
Theconceptofarraysisrelatedtothatofpointers.Infact,arraysworkverymuchlikepointerstotheirfirstelements,
and,actually,anarraycanalwaysbeimplicitlyconvertedtothepointerofthepropertype.Forexample,considerthese
twodeclarations:
1 intmyarray[20];
2 int*mypointer;
Thefollowingassignmentoperationwouldbevalid:
mypointer=myarray;
Afterthat,mypointerandmyarraywouldbeequivalentandwouldhaveverysimilarproperties.Themaindifferencebeing
thatmypointercanbeassignedadifferentaddress,whereasmyarraycanneverbeassignedanything,andwillalways
representthesameblockof20elementsoftypeint.Therefore,thefollowingassignmentwouldnotbevalid:
myarray=mypointer;
Let'sseeanexamplethatmixesarraysandpointers:
1 //morepointers
2 #include<iostream>
3 usingnamespacestd;
http://www.cplusplus.com/doc/tutorial/pointers/
10,20,30,40,50,
Edit
3/8
4/21/2015
PointersC++Tutorials
4
5
6
7
8
9
10
11
12
13
14
15
16
17
intmain()
{
intnumbers[5];
int*p;
p=numbers;*p=10;
p++;*p=20;
p=&numbers[2];*p=30;
p=numbers+3;*p=40;
p=numbers;*(p+4)=50;
for(intn=0;n<5;n++)
cout<<numbers[n]<<",";
return0;
}
Pointersandarrayssupportthesamesetofoperations,withthesamemeaningforboth.Themaindifferencebeingthat
pointerscanbeassignednewaddresses,whilearrayscannot.
Inthechapteraboutarrays,brackets([])wereexplainedasspecifyingtheindexofanelementofthearray.Well,infact
thesebracketsareadereferencingoperatorknownasoffsetoperator.Theydereferencethevariabletheyfollowjustas*
does,buttheyalsoaddthenumberbetweenbracketstotheaddressbeingdereferenced.Forexample:
1 a[5]=0;//a[offsetof5]=0
2 *(a+5)=0;//pointedby(a+5)=0
Thesetwoexpressionsareequivalentandvalid,notonlyifaisapointer,butalsoifaisanarray.Rememberthatifan
array,itsnamecanbeusedjustlikeapointertoitsfirstelement.
Pointerinitialization
Pointerscanbeinitializedtopointtospecificlocationsattheverymomenttheyaredefined:
1 intmyvar;
2 int*myptr=&myvar;
Theresultingstateofvariablesafterthiscodeisthesameasafter:
1 intmyvar;
2 int*myptr;
3 myptr=&myvar;
Whenpointersareinitialized,whatisinitializedistheaddresstheypointto(i.e.,myptr),neverthevaluebeingpointed
(i.e.,*myptr).Therefore,thecodeaboveshallnotbeconfusedwith:
1 intmyvar;
2 int*myptr;
3 *myptr=&myvar;
Whichanywaywouldnotmakemuchsense(andisnotvalidcode).
Theasterisk(*)inthepointerdeclaration(line2)onlyindicatesthatitisapointer,itisnotthedereferenceoperator(as
inline3).Boththingsjusthappentousethesamesign:*.Asalways,spacesarenotrelevant,andneverchangethe
meaningofanexpression.
Pointerscanbeinitializedeithertotheaddressofavariable(suchasinthecaseabove),ortothevalueofanother
pointer(orarray):
1 intmyvar;
2 int*foo=&myvar;
3 int*bar=foo;
Pointerarithmetics
Toconductarithmeticaloperationsonpointersisalittledifferentthantoconductthemonregularintegertypes.Tobegin
with,onlyadditionandsubtractionoperationsareallowedtheothersmakenosenseintheworldofpointers.Butboth
additionandsubtractionhaveaslightlydifferentbehaviorwithpointers,accordingtothesizeofthedatatypetowhich
theypoint.
Whenfundamentaldatatypeswereintroduced,wesawthattypeshavedifferentsizes.Forexample:charalwayshasa
sizeof1byte,shortisgenerallylargerthanthat,andintandlongareevenlargertheexactsizeofthesebeing
dependentonthesystem.Forexample,let'simaginethatinagivensystem,chartakes1byte,shorttakes2bytes,and
longtakes4.
Supposenowthatwedefinethreepointersinthiscompiler:
1 char*mychar;
2 short*myshort;
3 long*mylong;
andthatweknowthattheypointtothememorylocations1000,2000,and3000,respectively.
Therefore,ifwewrite:
1 ++mychar;
2 ++myshort;
3 ++mylong;
http://www.cplusplus.com/doc/tutorial/pointers/
4/8
4/21/2015
PointersC++Tutorials
mychar,asonewouldexpect,wouldcontainthevalue1001.Butnotsoobviously,myshortwouldcontainthevalue2002,
andmylongwouldcontain3004,eventhoughtheyhaveeachbeenincrementedonlyonce.Thereasonisthat,when
addingonetoapointer,thepointerismadetopointtothefollowingelementofthesametype,and,therefore,thesizein
bytesofthetypeitpointstoisaddedtothepointer.
Thisisapplicablebothwhenaddingandsubtractinganynumbertoapointer.Itwouldhappenexactlythesameifwe
wrote:
1 mychar=mychar+1;
2 myshort=myshort+1;
3 mylong=mylong+1;
Regardingtheincrement(++)anddecrement()operators,theybothcanbeusedaseitherprefixorsuffixofan
expression,withaslightdifferenceinbehavior:asaprefix,theincrementhappensbeforetheexpressionisevaluated,
andasasuffix,theincrementhappensaftertheexpressionisevaluated.Thisalsoappliestoexpressionsincrementing
anddecrementingpointers,whichcanbecomepartofmorecomplicatedexpressionsthatalsoincludedereference
operators(*).Rememberingoperatorprecedencerules,wecanrecallthatpostfixoperators,suchasincrementand
decrement,havehigherprecedencethanprefixoperators,suchasthedereferenceoperator(*).Therefore,thefollowing
expression:
*p++
isequivalentto*(p++).Andwhatitdoesistoincreasethevalueofp(soitnowpointstothenextelement),butbecause
++isusedaspostfix,thewholeexpressionisevaluatedasthevaluepointedoriginallybythepointer(theaddressit
pointedtobeforebeingincremented).
Essentially,thesearethefourpossiblecombinationsofthedereferenceoperatorwithboththeprefixandsuffixversions
oftheincrementoperator(thesamebeingapplicablealsotothedecrementoperator):
1
2
3
4
*p++//sameas*(p++):incrementpointer,anddereferenceunincrementedaddress
*++p//sameas*(++p):incrementpointer,anddereferenceincrementedaddress
++*p//sameas++(*p):dereferencepointer,andincrementthevalueitpointsto
(*p)++//dereferencepointer,andpostincrementthevalueitpointsto
Atypicalbutnotsosimplestatementinvolvingtheseoperatorsis:
*p++=*q++;
Because++hasahigherprecedencethan*,bothpandqareincremented,butbecausebothincrementoperators(++)
areusedaspostfixandnotprefix,thevalueassignedto*pis*qbeforebothpandqareincremented.Andthenbothare
incremented.Itwouldberoughlyequivalentto:
1 *p=*q;
2 ++p;
3 ++q;
Likealways,parenthesesreduceconfusionbyaddinglegibilitytoexpressions.
Pointersandconst
Pointerscanbeusedtoaccessavariablebyitsaddress,andthisaccessmayincludemodifyingthevaluepointed.Butitis
alsopossibletodeclarepointersthatcanaccessthepointedvaluetoreadit,butnottomodifyit.Forthis,itisenough
withqualifyingthetypepointedbythepointerasconst.Forexample:
1
2
3
4
5
intx;
inty=10;
constint*p=&y;
x=*p;//ok:readingp
*p=x;//error:modifyingp,whichisconstqualified
Hereppointstoavariable,butpointstoitinaconstqualifiedmanner,meaningthatitcanreadthevaluepointed,butit
cannotmodifyit.Notealso,thattheexpression&yisoftypeint*,butthisisassignedtoapointeroftypeconstint*.
Thisisallowed:apointertononconstcanbeimplicitlyconvertedtoapointertoconst.Butnottheotherwayaround!As
asafetyfeature,pointerstoconstarenotimplicitlyconvertibletopointerstononconst.
Oneoftheusecasesofpointerstoconstelementsisasfunctionparameters:afunctionthattakesapointertonon
constasparametercanmodifythevaluepassedasargument,whileafunctionthattakesapointertoconstas
parametercannot.
1 //pointersasarguments:
2 #include<iostream>
3 usingnamespacestd;
4
http://www.cplusplus.com/doc/tutorial/pointers/
11
21
31
Edit
5/8
4/21/2015
PointersC++Tutorials
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
voidincrement_all(int*start,int*stop)
{
int*current=start;
while(current!=stop){
++(*current);//incrementvaluepointed
++current;//incrementpointer
}
}
voidprint_all(constint*start,constint*stop)
{
constint*current=start;
while(current!=stop){
cout<<*current<<'\n';
++current;//incrementpointer
}
}
intmain()
{
intnumbers[]={10,20,30};
increment_all(numbers,numbers+3);
print_all(numbers,numbers+3);
return0;
}
Notethatprint_allusespointersthatpointtoconstantelements.Thesepointerspointtoconstantcontenttheycannot
modify,buttheyarenotconstantthemselves:i.e.,thepointerscanstillbeincrementedorassigneddifferentaddresses,
althoughtheycannotmodifythecontenttheypointto.
Andthisiswhereaseconddimensiontoconstnessisaddedtopointers:Pointerscanalsobethemselvesconst.Andthisis
specifiedbyappendingconsttothepointedtype(aftertheasterisk):
1
2
3
4
5
intx;
int*p1=&x;//nonconstpointertononconstint
constint*p2=&x;//nonconstpointertoconstint
int*constp3=&x;//constpointertononconstint
constint*constp4=&x;//constpointertoconstint
Thesyntaxwithconstandpointersisdefinitelytricky,andrecognizingthecasesthatbestsuiteachusetendstorequire
someexperience.Inanycase,itisimportanttogetconstnesswithpointers(andreferences)rightsoonerratherthan
later,butyoushouldnotworrytoomuchaboutgraspingeverythingifthisisthefirsttimeyouareexposedtothemixof
constandpointers.Moreusecaseswillshowupincomingchapters.
Toaddalittlebitmoreconfusiontothesyntaxofconstwithpointers,theconstqualifiercaneitherprecedeorfollowthe
pointedtype,withtheexactsamemeaning:
1 constint*p2a=&x;//nonconstpointertoconstint
2 intconst*p2b=&x;//alsononconstpointertoconstint
Aswiththespacessurroundingtheasterisk,theorderofconstinthiscaseissimplyamatterofstyle.Thischapterusesa
prefixconst,asforhistoricalreasonsthisseemstobemoreextended,butbothareexactlyequivalent.Themeritsofeach
stylearestillintenselydebatedontheinternet.
Pointersandstringliterals
Aspointedearlier,stringliteralsarearrayscontainingnullterminatedcharactersequences.Inearliersections,string
literalshavebeenusedtobedirectlyinsertedintocout,toinitializestringsandtoinitializearraysofcharacters.
Buttheycanalsobeaccesseddirectly.Stringliteralsarearraysoftheproperarraytypetocontainallitscharactersplus
theterminatingnullcharacter,witheachoftheelementsbeingoftypeconstchar(asliterals,theycanneverbe
modified).Forexample:
constchar*foo="hello";
Thisdeclaresanarraywiththeliteralrepresentationfor"hello",andthenapointertoitsfirstelementisassignedtofoo.
Ifweimaginethat"hello"isstoredatthememorylocationsthatstartataddress1702,wecanrepresenttheprevious
declarationas:
Notethatherefooisapointerandcontainsthevalue1702,andnot'h',nor"hello",although1702indeedisthe
addressofbothofthese.
Thepointerfoopointstoasequenceofcharacters.Andbecausepointersandarraysbehaveessentiallyinthesameway
inexpressions,foocanbeusedtoaccessthecharactersinthesamewayarraysofnullterminatedcharactersequences
are.Forexample:
1 *(foo+4)
2 foo[4]
Bothexpressionshaveavalueof'o'(thefifthelementofthearray).
Pointerstopointers
http://www.cplusplus.com/doc/tutorial/pointers/
6/8
4/21/2015
PointersC++Tutorials
C++allowstheuseofpointersthatpointtopointers,thatthese,initsturn,pointtodata(oreventootherpointers).
Thesyntaxsimplyrequiresanasterisk(*)foreachlevelofindirectioninthedeclarationofthepointer:
1
2
3
4
5
6
chara;
char*b;
char**c;
a='z';
b=&a;
c=&b;
This,assumingtherandomlychosenmemorylocationsforeachvariableof7230,8092,and10502,couldberepresented
as:
Withthevalueofeachvariablerepresentedinsideitscorrespondingcell,andtheirrespectiveaddressesinmemory
representedbythevalueunderthem.
Thenewthinginthisexampleisvariablec,whichisapointertoapointer,andcanbeusedinthreedifferentlevelsof
indirection,eachoneofthemwouldcorrespondtoadifferentvalue:
cisoftypechar**andavalueof8092
*cisoftypechar*andavalueof7230
**cisoftypecharandavalueof'z'
voidpointers
Thevoidtypeofpointerisaspecialtypeofpointer.InC++,voidrepresentstheabsenceoftype.Therefore,void
pointersarepointersthatpointtoavaluethathasnotype(andthusalsoanundeterminedlengthandundetermined
dereferencingproperties).
Thisgivesvoidpointersagreatflexibility,bybeingabletopointtoanydatatype,fromanintegervalueorafloattoa
stringofcharacters.Inexchange,theyhaveagreatlimitation:thedatapointedbythemcannotbedirectlydereferenced
(whichislogical,sincewehavenotypetodereferenceto),andforthatreason,anyaddressinavoidpointerneedstobe
transformedintosomeotherpointertypethatpointstoaconcretedatatypebeforebeingdereferenced.
Oneofitspossibleusesmaybetopassgenericparameterstoafunction.Forexample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//increaser
#include<iostream>
usingnamespacestd;
y,1603
Edit
voidincrease(void*data,intpsize)
{
if(psize==sizeof(char))
{char*pchar;pchar=(char*)data;++(*pchar);}
elseif(psize==sizeof(int))
{int*pint;pint=(int*)data;++(*pint);}
}
intmain()
{
chara='x';
intb=1602;
increase(&a,sizeof(a));
increase(&b,sizeof(b));
cout<<a<<","<<b<<'\n';
return0;
}
sizeofisanoperatorintegratedintheC++languagethatreturnsthesizeinbytesofitsargument.Fornondynamic
datatypes,thisvalueisaconstant.Therefore,forexample,sizeof(char)is1,becausecharishasalwaysasizeofone
byte.
Invalidpointersandnullpointers
Inprinciple,pointersaremeanttopointtovalidaddresses,suchastheaddressofavariableortheaddressofanelement
inanarray.Butpointerscanactuallypointtoanyaddress,includingaddressesthatdonotrefertoanyvalidelement.
Typicalexamplesofthisareuninitializedpointersandpointerstononexistentelementsofanarray:
1 int*p;//uninitializedpointer(localvariable)
2
3 intmyarray[10];
4 int*q=myarray+20;//elementoutofbounds
Neitherpnorqpointtoaddressesknowntocontainavalue,butnoneoftheabovestatementscausesanerror.InC++,
pointersareallowedtotakeanyaddressvalue,nomatterwhetherthereactuallyissomethingatthataddressornot.
Whatcancauseanerroristodereferencesuchapointer(i.e.,actuallyaccessingthevaluetheypointto).Accessingsuch
apointercausesundefinedbehavior,rangingfromanerrorduringruntimetoaccessingsomerandomvalue.
But,sometimes,apointerreallyneedstoexplicitlypointtonowhere,andnotjustaninvalidaddress.Forsuchcases,
thereexistsaspecialvaluethatanypointertypecantake:thenullpointervalue.ThisvaluecanbeexpressedinC++in
twoways:eitherwithanintegervalueofzero,orwiththenullptrkeyword:
1 int*p=0;
2 int*q=nullptr;
http://www.cplusplus.com/doc/tutorial/pointers/
7/8
4/21/2015
PointersC++Tutorials
Here,bothpandqarenullpointers,meaningthattheyexplicitlypointtonowhere,andtheybothactuallycompare
equal:allnullpointerscompareequaltoothernullpointers.ItisalsoquiteusualtoseethedefinedconstantNULLbe
usedinoldercodetorefertothenullpointervalue:
int*r=NULL;
NULLisdefinedinseveralheadersofthestandardlibrary,andisdefinedasanaliasofsomenullpointerconstantvalue
(suchas0ornullptr).
Donotconfusenullpointerswithvoidpointers!Anullpointerisavaluethatanypointercantaketorepresentthatitis
pointingto"nowhere",whileavoidpointerisatypeofpointerthatcanpointtosomewherewithoutaspecifictype.One
referstothevaluestoredinthepointer,andtheothertothetypeofdataitpointsto.
Pointerstofunctions
C++allowsoperationswithpointerstofunctions.Thetypicaluseofthisisforpassingafunctionasanargumentto
anotherfunction.Pointerstofunctionsaredeclaredwiththesamesyntaxasaregularfunctiondeclaration,exceptthat
thenameofthefunctionisenclosedbetweenparentheses()andanasterisk(*)isinsertedbeforethename:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//pointertofunctions
#include<iostream>
usingnamespacestd;
8
Edit
intaddition(inta,intb)
{return(a+b);}
intsubtraction(inta,intb)
{return(ab);}
intoperation(intx,inty,int(*functocall)(int,int))
{
intg;
g=(*functocall)(x,y);
return(g);
}
intmain()
{
intm,n;
int(*minus)(int,int)=subtraction;
m=operation(7,5,addition);
n=operation(20,m,minus);
cout<<n;
return0;
}
Intheexampleabove,minusisapointertoafunctionthathastwoparametersoftypeint.Itisdirectlyinitializedto
pointtothefunctionsubtraction:
int(*minus)(int,int)=subtraction;
Previous:
Charactersequences
Index
Next:
Dynamicmemory
Homepage|Privacypolicy
cplusplus.com,20002015Allrightsreservedv3.1
Spottedanerror?contactus
http://www.cplusplus.com/doc/tutorial/pointers/
8/8