双语版C++程序设计(第3版) 课件 9 Pointers and Dynamic Memory_第1页
双语版C++程序设计(第3版) 课件 9 Pointers and Dynamic Memory_第2页
双语版C++程序设计(第3版) 课件 9 Pointers and Dynamic Memory_第3页
双语版C++程序设计(第3版) 课件 9 Pointers and Dynamic Memory_第4页
双语版C++程序设计(第3版) 课件 9 Pointers and Dynamic Memory_第5页
已阅读5页,还剩40页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter9PointersandDynamicMemory

9.1VariableaddressesEveryvariableandobjectusedinaC++programisstoredinaspecificplaceinmemory.Eachlocationinmemoryhasauniqueaddressuses&togettheaddressofavariable9.1VariableaddressesHowthevariablesvar1andvar2arestoredinmemory?Differentcomputersmaygivedifferentaddressesfromtheonesabove.Variouscomputersandoperatingsystemswillstorevariablesatdifferentmemorylocations.Theaddressesareinhexadecimal(base16).9.2Pointervariables(指针变量)Apointervariableisavariablethatholdstheaddressofanothervariable.data_typeisanydatatype(suchaschar,int,float,astruct,aclassandsoon)variable_nameisanyvalidvariablename.Whitespaceinapointerdefinitionisnotrelevant.9.2PointervariablesPointerdefinitionsarereadbackwardsfromthevariablename,replacing*withthewords“isapointer”.int*int_ptrmeansthatint_ptrisapointertoanintfloat*float_ptrmeansthatfloat_ptrisapointertoafloat.9.2PointervariablesThetwovariablesptr1andptr2areusedtostoretheaddressesoftheothertwovariables,var1andvar2.9.3Thedereferenceoperator*(解引用运算符*)Thedereferenceoperator*isusedtoaccessthevalueofavariable,whoseaddressisstoredinapointer*ptrmeansthevalueofthevariableattheaddressstoredinthepointervariableptrInline9,the*isusedtodefineptrasapointertoanint.Inline13,the*isusedtoaccessthevalueofthememorylocation,theaddressofwhichisinptr.Line13displaysthevalueattheaddressheldinptrbyusingthedereferenceoperator*.Thisiscalleddereferencingthepointer

ptr.Thevalueof*ptristhesameasthevalueofvar.9.4UsingconstwithpointersWhendefiningapointer,thepointeritself,thevalueitpointstoorbothcanbemadeconstant.Thepositionofconstinthedefinitiondetermineswhichoftheseapply.Thedefinitionreadsas“pisapointertoanintegerconstant”.TheintegerisconstantandcannotbechangedusingpointerpThevalueoficanbechangedThepointermaybechanged9.4UsingconstwithpointersThisdefinitionofpreadsas“pisapointertoaconstantinteger”.thismeansthattheintegerisconstantandcannotbechangedusingpointerp.Thisdefinitionofpreads,“pisaconstantpointertoaninteger”.Thismeansthatthepointerisaconstantbutnotwhatitpointsto.9.4UsingconstwithpointersThisdefinitionofpreads,“pisaconstantpointertoanintegerconstant”.Thismeansthatboththepointerandtheintegeritpointstoareconstants.9.5Pointersandone-dimensionalarraysThenameofanarrayisapointertothefirstelementofthearray.Theelementsofthisarrayare:a[0],a[1],a[2],a[3],a[4]Thenameofthearrayaisequivalenttotheaddressofthefirstelement;aisthesameas&a[0]a+1istheaddressofthesecondelementa+2istheaddressofthethirdelement….9.5Pointersandone-dimensionalarraysAsthenameofanarrayisapointertothefirstelementofthearray,thedereferenceoperator*canbeusedtoaccesstheelementsofthearrayProgramExampleP9Etheexpression*(a+i)isnotequaltotheexpression*a+i9.5Pointersandone-dimensionalarraysUsepointerstoaccesstheelementsofanyarraynumbers[i]isequivalentto*(numbers+i).Althoughthenameofanarrayisapointertothefirstelementofthearray,youcannotchangeitsvalue;thisisbecauseitisaconstantpointer.a++ornumbers+=2areinvalid

9.5Pointersandone-dimensionalarraysAconstantmaybeaddedtoorsubtractedfromthevalueofapointer,allowingaccesstodifferentmemorylocations.Notallarithmeticoperationsarepermissibleonpointers.Themultiplicationoftwopointersisillegal,becausetheresultwouldnotbeavalidmemoryaddress.9.6Pointersandmulti-dimensionalarraysAccesstheelementsofamulti-dimensionalarrayusingpointers---increasinglycomplexAtwo-dimensionalarrayisstoredasan‘arrayofarrays’.Thismeansthataisaone-dimensionalarraywhoseelementsarethemselvesaone-dimensionalarraysofintegersThenameofatwo-dimensionalarrayisapointertothefirstelementofthearray.-------aisequivalentto&a[0]a[0]isitselfanarrayoftwointegers-------a[0]isequivalentto&a[0][0]9.6Pointersandmulti-dimensionalarraysa[0],a[1]anda[2]arepointers(datatypeisint*)andaisapointertoapointer(datatypeisint**).a[0]istheaddressofthefirstelementinthefirstrowofthearray.*a[0]isa[0][0],whichis4.a[1]istheaddressofthefirstelementinthesecondrow.*a[1]isa[1][0],whichis1.a[2]istheaddressofthefirstelementinthethirdrow.*a[2]isa[2][0],whichis9.9.6Pointersandmulti-dimensionalarraysa[0],a[1]anda[2]arepointers(datatypeisint*)andaisapointertoapointer(datatypeisint**).a[0]+1istheaddressofthesecondelementinthefirstrow.*(a[0]+1)isa[0][1],whichis6.*(a[1]+1)isa[1][1],whichis3.a[2]+1istheaddressofthesecondelementinthethirdrow.*(a[2]+1)isa[2][1],whichis7.a[1]+1istheaddressofthesecondelementinthesecondrow.9.6Pointersandmulti-dimensionalarrays*aisthesameasa[0]*(a+1)isthesameasa[1]*(a+2)isthesameasa[2]9.7Pointerstostructures(指向结构体的指针)DefineapointertoavariableofatypedefinedbystructorclassThegeneralformatfordefiningapointertoastructuretag_nameisthestructuretagvariable_nameisthenameofthepointervariableExample9.7PointerstostructuresDefineapointerptrtothestudent_recstructureAvaluecanbeassignedtoptrbyusingtheaddressoperator&Themembersofastructurevariablecanbereferencedbyusingthedereferenceoperator*.Notethatitistheaddressofthestructurevariablestudentandnottheaddressofthestructuretagstudent_recthatisassignedtoptrTheparenthesesarenecessary,becausetheselectionoperator.hasahigherprioritythanthedereferenceoperator*9.7PointerstostructuresForaccessingthemembersofastructure,thearrownotation->(-and>together)canbeusedinplaceofthedotnotationTheexpressionptr->numberreadsas“themembernumberofthestructurepointedtobyptr”.9.8PointerstoclassobjectsDefiningapointertoaclassobjectissimilartodefiningapointertoastructurevariable.class_nameisthenameoftheclass

variable_nameisthenameofthepointervariable.9.8PointerstoclassobjectsProgramP9FLine12definesac_ptrasapointertoabank_accountobjectLine14assignstheaddressofthebank_accountobjectactoac_ptr.9.8PointerstoclassobjectsThepublicmembersofaclassobjectmaybeaccessedbyusingthedereferenceoperator*.Thefirstpairofparenthesesarenecessary,becausetheselectionoperator.hasahigherprioritythanthedereferenceoperator*.Thearrownotation->canbeusedinplaceofthedotnotation->ismoreconvenientandcommon.9.9Pointersasfunctionarguments

(指针变量作为函数实参)ProgramExampleP9G:usespointersinplaceofreferencesLine19passestheaddressesofthetwofloating-pointvariablesnum1andnum2tothefunctionswap_vals().Theseaddressesarereceivedbytheparametersptr1andptr2,declaredaspointerstofloatsinthefunctionheaderonline24.Line26storesthevalueofnum1(=*ptr1)inthevariabletempLine28isequivalenttonum1=num2;Line29assignsthevalueoftemp(12.1)tonum2,because*ptr2isthesameasnum2.9.9PointersasfunctionargumentsItiseasiertousereferencesratherthanpointers&mustbeusedtopasstheaddressofthevariablestothefunctionWithinthefunctionthedereferenceoperator*mustbeusedtoaccessthevalueofeachofthenumbers.Thenumberoflibraryfunctionsusepointersasparametersctime(),convertingthetimeinsecondstoacharacterstringcontainingthedateandtime.9.9PointersasfunctionargumentsProgramExampleP9H9.10Dynamicmemoryallocation(动态内存分配)Problem:------Whendefininganarray,thenumberofelementsinthearraymustbespecified

inadvanceoftheprogramexecution.Sometimes,eitheralltheelementsspecifiedarenotusedormoreelementsthanwereoriginallyanticipatedarerequired.C++hastheabilitytoallocatememorywhileaprogramisexecutingUsingthememoryallocationoperatornew.9.10Dynamicmemoryallocation9.10.1AllocatingmemorydynamicallyforanarrayThenewmemoryallocationoperatorcanbeusedtoallocateacontiguous(连续的)blockofmemoryforanarrayofanydatatype,whetherthedatatypeisbuilt-inorisauser-definedstructureorclass.pointerisapointertotheallocatedmemorydata_typeisthedatatypeofthearray

sizeisthenumberofelementsinthearray9.10DynamicmemoryallocationWhenallocatingmemoryforanarrayofclassobjects,theremustbeadefaultconstructorfortheclasssothattheelementsofthearraygetinitialized.ProgramExampleP9I9.10DynamicmemoryallocationProgramExampleP9I…continuedLine15usesnewtoallocatetheexactnumberofelementsrequiredTheelementsofthenewlyallocatedarraycanbeaccessedusingeitherapointeroranindexTheallocatedmemoryisfreedusingthedeleteoperator.IMPORTANT:Includethesquarebrackets[]whenfreeingmemoryforapreviouslyallocatedarray.Withoutthesquarebrackets,onlythefirstelementofthearraywillbedeleted.9.10Dynamicmemoryallocation9.10.2InitializationwithnewWhenallocatingmemoryforanarrayofclassobjects,thedefaultconstructorfortheclassinitializestheelementsofthearray.DefaultconstructorforthebankaccountclassbeingcalledfivetimesNoinitializationisdonefordynamicallyallocatedarraysofbuilt-indatatypes9.10DynamicmemoryallocationSingleinstancesofanydatatype(built-in,auser-definedstructureoraclass)canbeinitializedusingasecondformofthenewoperator.pointerisapointertotheallocatedmemoryTheinitialvalueisoptionalAllocatememoryforaninteger,withaninitialvalueof100.Allocatememoryforaninteger,withnoinitialvalue.Allocatememoryforabankaccountobject.Thedefaultclassconstructoriscalledtodotheinitialization.Allocatememoryforabankaccountobject.Aconstructoriscalledtoassigninitialvaluestoaccountnumberandbalance.9.10DynamicmemoryallocationProgramExampleP9J9.10DynamicmemoryallocationProgramExampleP9J…continued9.10Dynamicmemoryallocation9.10.3Allocatingmemoryformulti-dimensionalarraysInC++,multi-dimensionalarraysareimplementedas‘arraysofarrays’.ProgramExampleP9K9.10DynamicmemoryallocationProgramExampleP9K…continuedLines44and47freethememoryallocatedinlines21and25separately.Foreachpointerreturnedfromnewinlines21and25thereisacorrespondingcalltodeletewiththatpointerinlines47and44.9.10Dynamicmemoryallocation9.10.4Outofmemoryerroritwasassumedthatthememoryrequestedwithnewwasallocated,regardlessofwhethermemorywasavailableornot.C++handlesinsufficientmemoryerrorsproducedbynewbycallingafunctionspecifiedinset_new_handler().ProgramExampleP9L9.10DynamicmemoryallocationLine27terminatestheprogramandexitstotheoperatingsystemwithastatuscodeof1.Anon-zerostatuscodeisusuallyusedtoindicateanabnormalexitfromaprogram.9.10DynamicmemoryallocationThefunctionout_of_memory()insertsanerrormessageintothestreamcerrratherthanintocout.Thestreamcerristypicallyusedforerrormessageswhilecoutisusedfordisplayingtheresultsofapro

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论