Sie sind auf Seite 1von 7

7/6/2015

PointerBasics

PointerBasics
ThisdocumentintroducesthebasicsofpointersastheyworkinseveralcomputerlanguagesC,C++,
Java,andPascal.ThisdocumentisthecompaniondocumentforthePointerFunwithBinkydigital
video,oritmaybeusedbyitself.
Section1Thethreebasicrulesofpointers
Section2Asimplecodeexample(thesameexampleusedinthevideo)
Section3Studyquestionswithsolutions
Thisisdocument106intheStanfordCSEducationLibrary.Thisandotherfreematerialsareavailableat
cslibrary.stanford.edu.Somedocumentsthatarerelatedtothisoneinclude...
PointerFunVideoasilly3minutedigitalvideoonthebasicsofpointers.Designedtogowith
thedocumentinfrontofyou.(http://cslibrary.stanford.edu/104/)
PointersandMemorya31pageexplanationofthecommonfeaturesandtechniquesforusing
pointersandmemoryinCandotherlanguages.(http://cslibrary.stanford.edu/102/)

Section1PointerRules
Oneofthenicethingsaboutpointersisthattheruleswhichgovernhowtheyworkareprettysimple.The
rulescanbelayeredtogethertogetcomplexresults,buttheindividualrulesremainsimple.

1)PointersandPointees
Apointerstoresareferencetosomething.Unfortunatelythereisnofixedtermforthethingthatthe
pointerpointsto,andacrossdifferentcomputerlanguagesthereisawidevarietyofthingsthatpointers
pointto.Weusethetermpointeeforthethingthatthepointerpointsto,andwesticktothebasic
propertiesofthepointer/pointeerelationshipwhicharetrueinalllanguages.Theterm"reference"means
prettymuchthesamethingas"pointer""reference"impliesamorehighleveldiscussion,while
"pointer"impliesthetraditionalcompiledlanguageimplementationofpointersasaddresses.Forthe
basicpointer/pointeerulescoveredhere,thetermsareeffectivelyequivalent.

Theabovedrawingshowsapointernamedxpointingtoapointeewhichisstoringthevalue42.A
pointerisusuallydrawnasabox,andthereferenceitstoresisdrawnasanarrowstartingintheboxand
leadingtoitspointee.
Allocatingapointerandallocatingapointeeforittopointtoaretwoseparatesteps.Youcanthinkofthe
pointer/pointeestructureasoperatingattwolevels.Boththelevelsmustbesetupforthingstowork.The
mostcommonerrorisconcentratingonwritingcodewhichmanipulatesthepointerlevel,butforgetting
tosetupthepointeelevel.Sometimespointeroperationsthatdonottouchthepointeesarecalled
"shallow"whileoperationsonthepointeesarecalled"deep".

2)Dereferencing
Thedereferenceoperationstartsatthepointerandfollowsitsarrowovertoaccessitspointee.Thegoal
http://cslibrary.stanford.edu/106/

1/7

7/6/2015

PointerBasics

maybetolookatthepointeestateortochangethepointeestate.
Thedereferenceoperationonapointeronlyworksifthepointerhasapointeethepointeemustbe
allocatedandthepointermustbesettopointtoit.Themostcommonerrorinpointercodeisforgetting
tosetupthepointee.Themostcommonruntimecrashbecauseofthaterrorinthecodeisafailed
dereferenceoperation.InJavatheincorrectdereferencewillbeflaggedpolitelybytheruntimesystem.In
compiledlanguagessuchasC,C++,andPascal,theincorrectdereferencewillsometimescrash,and
othertimescorruptmemoryinsomesubtle,randomway.Pointerbugsincompiledlanguagescanbe
difficulttotrackdownforthisreason.

3)PointerAssignment
Pointerassignmentbetweentwopointersmakesthempointtothesamepointee.Sotheassignmenty=
x;makesypointtothesamepointeeasx.Pointerassignmentdoesnottouchthepointees.Itjustchanges
onepointertohavethesamereferenceasanotherpointer.Afterpointerassignment,thetwopointersare
saidtobe"sharing"thepointee.

Section2Binky'sCodeExample
ThissectionpresentsthesamecodeexampleusedinthePointerFunWithBinkyvideo.Thereare
versionsofthecodeinseveralcomputerlanguages.Alltheversionshavethesamestructureand
demonstratethesamebasicrulesandlessonsaboutpointerstheyjustvaryintheirsyntax.Independent
ofanyparticularlanguage,thebasicstructureoftheexampleis...
1.Allocatetwopointersxandy.Allocatingthepointers
doesnotallocateanypointees.
2.Allocateapointeeandsetxtopointtoit.Each
languagehasitsownsyntaxforthis.Whatmattersisthat
memoryisdynamicallyallocatedforonepointee,andx
issettopointtothatpointee.
3.Dereferencextostore42initspointee.Thisisabasic
exampleofthedereferenceoperation.Startatx,follow
thearrowovertoaccessitspointee.
4.Trytodereferenceytostore13initspointee.This
crashesbecauseydoesnothaveapointeeitwasnever
assignedone.

5.Assigny=x;sothatypointstox'spointee.Nowx
andypointtothesamepointeetheyare"sharing".
6.Trytodereferenceytostore13initspointee.This
timeitworks,becausethepreviousassignmentgaveya
pointee.
http://cslibrary.stanford.edu/106/

2/7

7/6/2015

PointerBasics

Versions
BelowareversionsofthisexampleinC,Java,C++,andPascal.Theyalldothesamethingthesyntax
isjustadjustedforeachlanguage.

CVersion
Thepointersxandyareallocatedaslocalvariables.Thetypeint*means"pointerwhichpointstoints".
AsBinkylearns,thepointersdonotautomaticallygetpointees.Thepointeeforxisdynamically
allocatedseparatelywiththestandardlibraryfunctionmalloc().Thesyntax*xdereferencesxtoaccess
itspointee.
voidmain(){
int*x;//Allocatethepointersxandy
int*y;//(butnotthepointees)

x=malloc(sizeof(int));//Allocateanintpointee,
//andsetxtopointtoit

*x=42;//Dereferencextostore42initspointee

*y=13;//CRASHydoesnothaveapointeeyet

y=x;//Pointerassignmentsetsytopointtox'spointee

*y=13;//Dereferenceytostore13inits(shared)pointee
}

AnotherwaytoplaywithpointersinC(orC++)isusingtheampersand(&)operatortocomputeapointer
tolocalmemoryinthestack.However,pointeesdynamicallyallocatedintheheaparethemostcommon,
sothat'swhatweshow.

JavaVersion
InJava,themostcommonpointer/pointeestructureisalocalvariablepointerwhichpointstoapointee
objectofsomeclass.Soinkeepingwithourplantocreateapointeewhichstoresaninteger,wedefine
anIntObjclassthatstoresoneinteger.WecanthencreateanIntObjpointeetostoretheint.AsBinky
learns,allocatingthepointerwithcodelikeIntObjx;doesnotautomaticallyallocatethepointee.The
IntObjpointeeisallocatedwithacalltonew.Thesyntaxx.valuedereferencesxtoaccessthe.valuefield
initspointee.
classIntObj{
publicintvalue;
}
publicclassBinky(){
publicstaticvoidmain(String[]args){
IntObjx;//Allocatethepointersxandy
http://cslibrary.stanford.edu/106/

3/7

7/6/2015

PointerBasics

IntObjy;//(butnottheIntObjpointees)

x=newIntObj();//AllocateanIntObjpointee
//andsetxtopointtoit

x.value=42;//Dereferencextostore42initspointee

y.value=13;//CRASHydoesnothaveapointeeyet

y=x;//Pointerassignmentsetsytopointtox'spointee

y.value=13;//Deferenceytostore13inits(shared)pointee
}
}

C++Version
TheonlydifferenceinthisversionfromtheCversionaboveisthatthestandardoperatornewisused
insteadofmalloc().
voidmain(){
int*x;//Allocatethepointersxandy
int*y;//(butnotthepointees)

x=newint;//Allocateanintpointee,
//andsetxtopointtoit

*x=42;//Dereferencextostore42initspointee

*y=13;//CRASHydoesnothaveapointeeyet

y=x;//Pointerassignmentsetsytopointtox'spointee

*y=13;//Dereferenceytostore13inits(shared)pointee
}

PascalVersion
ThisisstructurallyidenticaltotheCversion,butwithPascalsyntax.Thetype^Integermeans"pointer
whichpointstointegers".AsBinkylearns,allocatingthepointerdoesnotautomaticallyallocateits
pointee.ThestandardprocedureNew()takesapointerargument,allocatesanewpointee,andsetsthe
pointertopointtoit.Theexpressionx^dereferencesxtoaccessitspointee.
Proceduremain
varx:^Integer;/*Allocatethepointersxandy*/
vary:^Integer;/*(butnotthepointees)*/
Begin
New(x);/*Allocateapointeeandsetxtopointtoit*/

x^:=42;/*Deferencextostore42initspointee*/

y^:=13;/*CRASHydoesnothaveapointeeyet*/

y:=x;
/*Pointerassignmentmakesypointtox'spointee*/

y^:=13;/*Dereferenceytostore13inits(shared)pointee*/
End;
http://cslibrary.stanford.edu/106/

4/7

7/6/2015

PointerBasics

Section3StudyQuestions
Thesestudyquestionscoverreviewbasicfeaturesofpointers.Twoofthequestionsmakeheavyuseof
memorydrawings.Memorydrawingsareanexcellentwaytothinkthroughpointerproblems.

Question1
Attheendoftheabovecode,yissettohaveapointeeandthendereferenceditstorethenumber13into
itspointee.Afterthishappens,whatisthevalueofx'spointee?
Answer:Thevalueofx'spointeeis13becauseitisalsoy'spointee.Thisiswhatsharingisallabout
multiplepointerspointingtoonepointee.

Question2
Considerthefollowingdrawing...

Usingthelanguageofyourchoice,writesomecodethatcreatestheabovepointerstructure.
Answer:Thebasicstepsare...
1. Allocatetwopointers.
2. Allocatetwopointeesandsetthepointerstopointtothem.
3. Storethenumbers1and2intothepointees.
4. Assignthefirstpointertopointtothesecondpointee.This"loses"thereferencetothefirstpointee
whichisunusual,butthat'swhatthequestioncallsfor.
CCode

JavaCode

int*x;
int*y;

IntObjx;
IntObjy;

x=malloc(sizeof(int));
y=malloc(sizeof(int));

x=newIntObj();
y=newIntObj();

*x=1;
*y=2;

x.value=1;
y.value=2;

x=y;

x=y;

Question3
Supposeyouhaveapointeetypecalled"Node"whichcontainstwothings:anint,andapointerto
http://cslibrary.stanford.edu/106/

5/7

7/6/2015

PointerBasics

anotherNode(thedeclarationforsuchaNodetypeisgivenbelow).Withsuchapointeetype,youcould
arrangethreeNodepointeesinastructurewheretheywerepointingtoeachotherlikethis...

ThepointernamedxpointstothefirstNodepointee.ThefirstNodecontainsapointertothesecond,the
secondcontainsapointertothethird,andthethirdcontainsapointerbacktothefirst.Thisstructurecan
bebuildusingonlytherulesofpointeeallocation,dereferencing,andassignmentthatwehaveseen.
Usingthedeclarationbelow,eachNodecontainsanintegernamedvalueandapointertoanotherNode
namednext.
CCode
JavaCode
structNode{

intvalue;

structNode*next;
};

classNode{

publicintvalue;

publicNodenext;
};

Writethecodetobuildthestructureintheabovedrawing.Forconvenience,youmayusetemporary
pointersinadditiontox.TheonlynewsyntaxrequiredisthatinC,theoperator>dereferencesapointer
toaccessafieldinthepointeeso>valueaccessesthefieldnamedvalueinx'spointee.
AnswerThebasicstepsare...
1. Allocatethreepointers:xforthefirstNode,andtemporarypointersyandzfortheothertwo
Nodes.
2. AllocatethreeNodepointeesandstorereferencestotheminthethreepointers.
3. Dereferenceeachpointertostoretheappropriatenumberintothevaluefieldinitspointee.
4. Dereferenceeachpointertoaccessthe.nextfieldinitspointee,andusepointerassignmenttoset
the.nextfieldtopointtotheappropriateNode.
CCode

JavaCode

//Allocatethepointers
structNode*x;
structNode*y;
structNode*z;

//Allocatethepointers
Nodex;
Nodey;
Nodez;

//Allocatethepointees
x=malloc(sizeof(Node));
y=malloc(sizeof(Node));
z=malloc(sizeof(Node));

//Allocatethepointees
x=newNode();
y=newNode();
z=newNode();

//Putthenumbersinthepointees
x>value=1;
y>value=2;
z>value=3;

//Putthenumbersinthepointees
x.value=1;
y.value=2;
z.value=3;

http://cslibrary.stanford.edu/106/

6/7

7/6/2015

PointerBasics

//Putthepointersinthepointees
x>next=y;
y>next=z;
z>next=x;

//Putthepointersinthepointees
x.next=y;
y.next=z;
z.next=x;

TheNodestructureintroducedhereisactuallyarealdatatypeusedtobuildthe"linkedlist"data
structure.Linkedlistsarearealisticapplieduseofpointersandareanexcellentareatodevelopyour
pointerskills.SeeLinkedListBasicsandLinkedListProblemsintheStanfordCSEducationLibraryfor
lotsoflinkedlistmaterial.

Postscript
CopyrightNickParlante,1999.Thismaterialmaybecopiedandredistributedsolongasthestandard
StanfordCSEducationLibrarynoticeonthefirstpageisretained:"Thisisdocument106intheStanford
CSEducationLibrary.Thisandotherfreematerialsareavailableatcslibrary.stanford.edu."
Ihopethatyoubenefitfromthismaterialinthespiritofgoodwillinwhichitisgiven.Thatsomeone
seekingeducationshouldhavetheopportunitytofindit.
UptotheCSEducationLibraryHome

http://cslibrary.stanford.edu/106/

7/7

Das könnte Ihnen auch gefallen