36
Pointers CS 16: Solving Problems with Computers I Lecture #12 Ziad Matni Dept. of Computer Science, UCSB

CS16 Lecture12 Pointers · • Thursday, 5/17 in this classroom • Starts at 2:00 PM **SHARP** – Please start arriving 5-10 minutes before class • I may ask you to change seats

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Pointers

CS16:SolvingProblemswithComputersILecture#12

ZiadMatni

Dept.ofComputerScience,UCSB

•  Thursday,5/17inthisclassroom•  Startsat2:00PM**SHARP**

–  Pleasestartarriving5-10minutesbeforeclass•  Imayaskyoutochangeseats•  PleasebringyourUCSBIDswithyou

•  Closedbook:nocalculators,nophones,nocomputers•  OnlyallowedONE8.5”x11”sheetofnotes–onesidedonly

–  Youhavetoturnitinwithyourexam•  Youwillwriteyouranswersontheexamsheetitself.5/15/18 Matni,CS16,Sp18 2

What’sontheMidterm#2?EVERYTHINGFromLectures7–12,including…

•  Makefiles

•  DebugTechniques

•  NumericalConversions

•  Strings:C++vsC-strings

•  StringsandCharacters:MemberFunctions&Manipulators

•  FileI/O

•  Arrays

•  Pointers(whateverwefinishtoday)

5/15/18 Matni,CS16,Sp18 3

LectureOutline

•  Pointers

5/15/18 Matni,CS16,Sp18 4

Pointers

•  Apointeristhememoryaddressofavariable

•  Whenavariableisusedasacall-by-referenceargument,it’stheactualaddressinmemorythatispassed

5/15/18 Matni,CS16,Sp18 5

MemoryAddresses

•  Theaddressofavariablecanbeobtainedbyputtingtheampersandcharacter(&)beforethevariablename.

•  &iscalledtheaddress-ofoperator

•  So,whilenum=42,&num=0x1F=31

•  Youcanassignavariabletoanaddress-ofanothervariabletoo!•  Example:num_add=&num

5/15/18 Matni,CS16,Sp18 6

Address Data0x001D 00x001E -250x001F 420x0020 13320x0021 -40090x0022 7… …

0x98A0 31

1byte

num

num_add

MemoryAddress

Recall:num=42andnum_add=&num=0x001F

•  Thevariablethatstorestheaddressofanothervariable(likenum_add)iscalledapointer.

5/15/18 Matni,CS16,Sp18 7

42num

num_add

DereferenceOperator(*)

•  Pointers“pointto”thevariablewhoseaddresstheystore•  Pointerscanaccessthevariabletheypointtodirectly•  Thisaccessisdonebyprecedingthepointernamewiththe

dereferenceoperator(*)–  Theoperatoritselfcanbereadas“valuepointedtoby”

•  So,while num_add=0x001F *num_add=42

5/15/18 Matni,CS16,Sp18 8

42num

num_add

Pointers

AGAIN:•  Apointeristhememoryaddressofavariable

•  Whenavariableisusedasacall-by-referenceargument,it’stheactualaddressinmemorythatispassed

5/15/18 Matni,CS16,Sp18 9

PointersTellUs(ortheCompiler)WhereToFindAVariable

•  Pointers"point"toavariablebytellingwherethevariableislocated

5/15/18 Matni,CS16,Sp18 10

DeclaringPointers

•  Pointervariablesmustbedeclaredtohaveapointertype

•  Example:Todeclareapointervariablepthatcan"point"toavariableoftypedouble:

double*p;

•  Theasterisk(*)identifiespasapointervariable

5/15/18 Matni,CS16,Sp18 11

MultiplePointerDeclarations

•  Todeclaremultiplepointersinastatement,usetheasteriskbeforeeachpointervariable

•  Example: int*p1,*p2,v1,v2;p1andp2pointtovariablesoftypeintv1andv2arevariablesoftypeint

5/15/18 Matni,CS16,Sp18 12

Theaddress-ofOperator

•  The&operatorcanbeusedtodeterminetheaddressofavariablewhichcanbeassignedtoapointervariable

•  Example:p1=&v1;p1isnowapointertov1v1canbecalled“thevariablepointedtobyp1”

5/15/18 Matni,CS16,Sp18 13

APointerExample

v1=0;p1=&v1;*p1=42;cout<<v1<<endl;cout<<*p1<<endl; output: 42

42

5/15/18 Matni,CS16,Sp18 14

v1 and *p1 now refer to the same variable

0v1 p1

42v1 p1

PointerAssignment

•  Theassignmentoperator=isusedtoassignthevalueofonepointertoanother

Example:Ifp1stillpointstov1(previousslide)thenthestatement

p2=p1;

causes*p2,*p1,andv1alltonamethesamevariable

5/15/18 Matni,CS16,Sp18 15

42v1 p2=p1

Caution!PointerAssignments

•  Somecareisrequiredmakingassignmentstopointervariables

Assumingp1andp3arepointers p1=p3; //changesthelocationthatp1"points"to*p1=*p3;//changesthevalueatthelocationthat //p1"points"to

5/15/18 Matni,CS16,Sp18 16

UsesoftheAssignmentOperatoronPointers

5/15/18 Matni,CS16,Sp18 17

UsesoftheAssignmentOperatoronPointers

5/15/18 Matni,CS16,Sp18 18

PointerAssignment–Example1

Considerthiscode:int*p1,*p2,x;p1=&x;p2=p1;Whichfigurebestrepresentsthiscode?A.  FigureAB.  FigureBC.  Neither:thecodeisincorrect

5/15/18 Matni,CS16,Sp18 19

x

p1 p2

x

p1 p2

FigureA FigureB

PointerAssignment–Example2

intx=10,y=20;int*p1=&x,*p2=&y;p2=p1;int**p3;p3=&p2;Q:HowcanIprintoutthevalue"10"usingp2?A:cout<<*p2;Q:HowcanIprintoutthevalue"10"usingp3?A:cout<<**p3;

5/15/18 Matni,CS16,Sp18 20

10 20

x y

p1 p2

10 20

x y

p1 p2 p3

PassingbyPointers!ABetterWay!voidswapValue(int*x,int*y){inttmp=*x;*x=*y;*y=tmp;

}intmain(){inta(30),b(40);cout<<a<<""<<b<<endl;swapValue(&a,&b);cout<<a<<""<<b<<endl;

}5/15/18 Matni,CS16,Sp18 21

5/15/18 Matni,CS16,Sp18 22

ThenewOperator

•  Usingpointers,variablescanbemanipulatedevenifthereisnoidentifierforthem

•  Tocreateapointertoanew“nameless”variableoftypeint: p1=newint;

•  Thenewvariableisreferredtoas*p1•  *p1canbeusedanyplaceanintegervariablecanExample: cin>>*p1; *p1=*p1+7;

5/15/18 Matni,CS16,Sp18 23

DynamicVariables

•  Variablescreatedusingthenewoperatorarecalleddynamicvariables

•  Dynamicvariablesarecreatedanddestroyedwhiletheprogramisrunning

•  Wedon’thavetobotherwithnamingthem,justtheirpointers

5/15/18 Matni,CS16,Sp18 24

42p1p2 53

88

42p1p2 53

88

BasicMemoryManagement:TheHeap

•  Anareaofmemorycalledthefreestoreortheheapisreservedfordynamicvariables– Newdynamicvariablesusememoryintheheap–  Ifalloftheheapisused,callstonewwillfail–  Soyouneedtomanageyourunuseddynamicvariables…

•  Un-neededmemorycanberecycled– Whenvariablesarenolongerneeded,theycanbedeletedandthememory

theyusedisreturnedtotheheap

5/15/18 Matni,CS16,Sp18 27

ThedeleteOperator

•  Whendynamicvariablesarenolongerneeded,deletethemtoreturnmemorytotheheap

•  Example: deletep;

•  Thevalueofpisnowundefinedandthememoryusedbythevariablethatppointedtoisbackintheheap

5/15/18 Matni,CS16,Sp18 28

DanglingPointers

•  Usingdeleteonapointervariabledestroysthedynamicvariablepointedto(freesupmemorytoo!)

•  Ifanotherpointervariablewaspointingtothedynamicvariable,thatvariableisalsonowundefined

•  Undefinedpointervariablesarecalleddanglingpointers– Dereferencingadanglingpointer(*p)isusuallydisastrous

5/15/18 Matni,CS16,Sp18 29

AutomaticVariables

•  Asyouknow:variablesdeclaredinafunctionarecreatedbyC++andthendestroyedwhenthefunctionends–  Thesearecalledautomaticvariables

•  However,theprogrammermustmanuallycontrolcreationanddestructionofpointervariableswithoperatorsnewanddelete

5/15/18 Matni,CS16,Sp18 30

TypeDefinitions

•  Anamecanbeassignedtoatypedefinition,thenusedtodeclarevariables

•  Thekeywordtypedefisusedtodefinenewtypenames

•  Syntax:typedefKnown_Type_DefinitionNew_Type_Name; where,Known_Type_Definitioncanbeanydatatype

5/15/18 Matni,CS16,Sp18 31

DefiningPointerTypes

•  Tohelpavoidmistakesusingpointers,defineapointertypename

•  Example:typedefint*IntPtr;Definesanewtype,IntPtr,forpointervariablescontainingpointerstointvariables

IntPtrp;isnowequivalenttosaying:int*p;

5/15/18 Matni,CS16,Sp18 32

MultipleDeclarationsAgain

•  Usingournewpointertypedefinedastypedefint*IntPtr; Helpspreventerrorsinpointerdeclaration

•  Forexample,ifyouwanttodeclare2pointers,insteadofthis:int*p1,p2; //Careful!Onlyp1isapointervariable!dothis:

IntPtrp1; intp2;

5/15/18 Matni,CS16,Sp18 33

PointerReferenceParameters

•  Asecondadvantageinusingtypedeftodefineapointertypeisseeninparameterlistsinfunctions,like…

•  Example: voidsample_function(IntPtr&pointer_var);

islessconfusingthan: voidsample_function(int*&pointer_var);

5/15/18 Matni,CS16,Sp18 34

YOURTO-DOs

q StartLab7onWednesdayq DoHW12bynextTuesdayq StudyforyourMidterm#2onThursday!

q VisitProf’sandTAs‘officehoursifyouneedhelp!

q Sleepmorethanyoustudy.Studymorethanyouparty.Anddon’tforgettoparty…

5/15/18 Matni,CS16,Sp18 35

5/15/18 Matni,CS16,Sp18 36