




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年特种结构 试题及答案
- 2025年科学科技的知识竞赛题库
- 2025年投融资管理考试题及答案
- 2025年师德个人修养试题及答案
- 2025年百科知识竞赛题库较难
- 2025年云南省道路运输企业主要负责人安全考试练习题附答案
- 2025二建《工程法规》历年高频真题及答案
- 2025年制冷与空调设备运行操作复审考试及考试题库含答案参考
- 2025年长途代驾笔试题及答案
- 2025年竞赛几何奥赛真题
- 110kV变电站施工材料采购方案
- 《风暴潮地理》课件
- 保险钱教育金课件
- 建筑工程质量检测与评估规程
- 物资搬运服务方案
- 2025年高考地理一轮复习备考策略
- 律师事务所案件管理系统操作指南
- 微型消防站消防应急预案
- 高中英语语法大全总结
- 医院消毒隔离知识培训课件
- 知识题库-机动车检测站授权签字人试题库及答案
评论
0/150
提交评论