




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Chapter 9Pointers and Dynamic ArraysOverview9.1 Pointers9.2 Dynamic ArraysSlide 9- 39.1PointersPointersA pointer is the memory address of a variable Memory addresses can be used as names for variables If a variable is stored in three memory locations, the address of the first can be used as a name f
2、or the variable. When a variable is used as a call-by-reference argument, its address is passed Slide 9- 5Pointers Tell Where To Find A VariableAn address used to tell where a variable is storedin memory is a pointerPointers point to a variable by telling where the variable is locatedSlide 9- 6Decla
3、ring PointersPointer variables must be declared to have a pointer typeExample: To declare a pointer variable p that can point to a variable of type double: double *p;The asterisk identifies p as a pointer variableSlide 9- 7Multiple Pointer DeclarationsTo declare multiple pointers in a statement, use
4、the asterisk before each pointer variableExample: int *p1, *p2, v1, v2;p1 and p2 point to variables of type intv1 and v2 are variables of type intSlide 9- 8The address of OperatorThe & operator can be used to determine the address of a variable which can be assigned to a pointer variableExample: p1
5、= &v1; p1 is now a pointer to v1 v1 can be called v1 or the variable pointed to by p1Slide 9- 9The Dereferencing OperatorC+ uses the * operator in yet another way withpointersThe phrase The variable pointed to by p is translated into C+ as *pHere the * is the dereferencing operatorp is said to be de
6、referencedSlide 9- 10A Pointer Examplev1 = 0;p1 = &v1;*p1 = 42;cout v1 endl;cout *p1 *p1; *p1 = *p1 + 7;Slide 9- 14Dynamic VariablesVariables created using the new operator arecalled dynamic variablesDynamic variables are created and destroyed while the program is runningAdditional examples of point
7、ers and dynamic variables are shown in An illustration of the code in Display 9.2 is seen in Slide 9- 15Display 9.2Display 9.3new and Class TypesUsing operator new with class types callsa constructor as well as allocating memoryIf MyType is a class type, then MyType *myPtr; / creates a pointer to a
8、/ variable of type MyType myPtr = new MyType; / calls the default constructor myPtr = new MyType (32.0, 17); / calls Mytype(double, int);Slide 9- 16Basic Memory ManagementAn area of memory called the freestore or the heap is reserved for dynamic variablesNew dynamic variables use memory in the frees
9、toreIf all of the freestore is used, calls to new will failUnneeded memory can be recycledWhen variables are no longer needed, they can be deleted and the memory they used is returned to the freestoreSlide 9- 17The delete OperatorWhen dynamic variables are no longer needed, delete them to return mem
10、ory to the freestoreExample: delete p;The value of p is now undefined and the memory used by the variable that p pointed to is back in the freestoreSlide 9- 18Dangling PointersUsing delete on a pointer variable destroys the dynamic variable pointed toIf another pointer variable was pointing to the d
11、ynamic variable, that variable is also undefinedUndefined pointer variables are calleddangling pointers Dereferencing a dangling pointer (*p) is usuallydisasterousSlide 9- 19Automatic VariablesVariables declared in a function are created by C+ and destroyed when the function endsThese are called aut
12、omatic variables because their creation and destruction is controlled automaticallyThe programmer manually controls creation and destruction of pointer variables with operatorsnew and delete Slide 9- 20Global VariablesVariables declared outside any function definition are global variablesGlobal vari
13、ables are available to all parts of a programGlobal variables are not generally usedSlide 9- 21Type DefinitionsA name can be assigned to a type definition, then used to declare variablesThe keyword typedef is used to define new type namesSyntax: typedef Known_Type_Definition New_Type_Name;Known_Type
14、_Definition can be any typeSlide 9- 22Defining Pointer TypesTo avoid mistakes using pointers, define a pointer type nameExample: typedef int* IntPtr; Defines a new type, IntPtr, for pointer variables containing pointers to int variablesIntPtr p;is equivalent toint *p; Slide 9- 23Multiple Declaration
15、s AgainUsing our new pointer type defined as typedef int* IntPtr;Prevent this error in pointer declaration: int *P1, P2; / Only P1 is a pointer variable with IntPtr P1, P2; / P1 and P2 are pointer / variablesSlide 9- 24Pointer Reference ParametersA second advantage in using typedef to define a point
16、er type is seen in parameter listsExample: void sampleFunction(IntPtr& pointerVar); is less confusing than void sampleFunction( int*& pointerVar);Slide 9- 25Section 9.1 ConclusionCan youDeclare a pointer variable?Assign a value to a pointer variable?Use the new operator to create a new variable in t
17、he freestore?Write a definition for a type called NumberPtr to be a type for pointers to dynamic variables of type int?Use the NumberPtr type to declare a pointer variable called myPoint?Slide 9- 269.2Dynamic ArraysDynamic ArraysA dynamic array is an array whose size is determined when the program i
18、s running, not when you write the programSlide 9- 28Pointer Variables and Array VariablesArray variables are actually pointer variables that point to the first indexed variableExample: int a10; typedef int* IntPtr; IntPtr p;Variables a and p are the same kind of variableSince a is a pointer variable
19、 that points to a0, p = a;causes p to point to the same location as aSlide 9- 29Pointer Variables As Array VariablesContinuing the previous example:Pointer variable p can be used as if it were an array variableExample: p0, p1, p9 are all legal ways to use pVariable a can be used as a pointer variabl
20、e except the pointer value in a cannot be changedThis is not legal: IntPtr p2; / p2 is assigned a value a = p2 / attempt to change aSlide 9- 30Display 9.4Display 9.5Creating Dynamic ArraysNormal arrays require that the programmer determine the size of the array when the programis writtenWhat if the
21、programmer estimates too large?Memory is wastedWhat if the programmer estimates too small?The program may not work in some situationsDynamic arrays can be created with just the right size while the program is runningSlide 9- 31Creating Dynamic ArraysDynamic arrays are created using the new operatorE
22、xample: To create an array of 10 elements of type double: typedef double* DoublePtr; DoublePtr d; d = new double10; d can now be used as if it were an ordinary array! Slide 9- 32This could be an integer variable!Dynamic Arrays (cont.)Pointer variable d is a pointer to d0When finished with the array,
23、 it should be deleted to return memory to the freestoreExample: delete d;The brackets tell C+ a dynamic array is being deleted so it must check the size to know how many indexed variables to removeForgetting the brackets, is not legal, but would tell the computer to remove only one variableSlide 9-
24、33Display 9.6 (1)Display 9.6 (2)Pointer Arithmetic (Optional)Arithmetic can be performed on the addresses contained in pointersUsing the dynamic array of doubles, d, declared previously, recall that d points to d0The expression d+1 evaluates to the address of d1 and d+2 evaluates to the address of d
25、2Notice that adding one adds enough bytes for onevariable of the type stored in the array Slide 9- 34Pointer Arthmetic OperationsYou can add and subtract with pointersThe + and - - operators can be usedTwo pointers of the same type can be subtracted to obtain the number of indexed variables betweenT
26、he pointers should be in the same array!This code shows one way to use pointer arithmetic: for (int i = 0; i array_size; i+) cout *(d + i) ; / same as cout di ;Slide 9- 35Multidimensional Dynamic ArraysTo create a 3x4 multidimensional dynamic arrayView multidimensional arrays as arrays of arraysFirs
27、t create a one-dimensional dynamic arrayStart with a new definition: typedef int* IntArrayPtr;Now create a dynamic array of pointers named m: IntArrayPtr *m = new IntArrayPtr3;For each pointer in m, create a dynamic array of ints for (int i = 0; i3; i+) mi = new int4;Slide 9- 36The dynamic array created on the previous slidecould be visualized like this:A Multidimensial Dynamic ArraySlide 9- 37mIntArrayPtrs intsIntArrayPtr *DeletingMultidimensional ArraysTo delete a multidimens
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 临床医院实习报告总结范文
- 2025年地震观测设备项目合作计划书
- 2025年镍镉电池项目建议书
- 2025届上海市桃浦中学 高一物理第二学期期末复习检测模拟试题含解析
- 打造智慧办公生态圈如何运用区块链技术实现高效身份验证
- 广东省广州市广东第二师范学院番禺中2025届高一物理第二学期期末达标检测模拟试题含解析
- 心理驱动的学习教育心理学的新视角
- 学习动机与学习潜能的深度解析
- 专题04 荐信 感谢信 倡议书(测试)(原卷版)-2025年高考英语二轮复习
- 教育技术的前沿个性化学习与评估的挑战与机遇
- 纱线测试与质量控制技术
- (完整版)小学六年级奥数应用题100道附答案
- HG/T 6313-2024 化工园区智慧化评价导则(正式版)
- 地籍图的测绘
- 商业道德承诺书
- GB/T 4074.6-2024绕组线试验方法第6部分:热性能
- 浅析汕头市内衣产业的现状、问题和对策
- DB11/T 147-2015-检查井盖结构、安全技术规范
- JJG 875-2019数字压力计行业标准
- 创新型QC成果课件
- 公务用车定点维修服务质量保障方案
评论
0/150
提交评论