CC++:从基础语法到优化策略 (5).pdf

上传人:奉*** 文档编号:67731970 上传时间:2022-12-26 格式:PDF 页数:28 大小:3.34MB
返回 下载 相关 举报
CC++:从基础语法到优化策略 (5).pdf_第1页
第1页 / 共28页
CC++:从基础语法到优化策略 (5).pdf_第2页
第2页 / 共28页
点击查看更多>>
资源描述

《CC++:从基础语法到优化策略 (5).pdf》由会员分享,可在线阅读,更多相关《CC++:从基础语法到优化策略 (5).pdf(28页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、C/C+Program DesignCS205Week 5Content Pointer Allocate Memory:C Style Allocate Memory:C+Style Managing memory for dataPointersThe slides are based on the book Whats a pointer?Three fundamental properties of declaration Where the information is stored What value is kept there What type of information

2、is stored How to know where the values are stored?Using address operator&to access the address Using hexadecimal notation to display the address valuesRun program example address.cppaddressPointer Type Using ordinary variablesNaturally,the value is treated as a namedquantityThe location as the deriv

3、ed quantity Using new strategy:pointer typeInverse way Operator of asterisk*:Indirect valueThe dereferencing operator Program example pointer.cppImportance of pointers One essential to the C/C+programming philosophy of is the memory managementmemory management Pointers would be the C/C+Philosophy Yo

4、u can access memory more directly than Java,Python,etcto gain efficiency.Declaring and Initializing Pointers Example:int*birddog;*birddog is a int type variable birddog is a pointer type variable The type for birddog is pointer-to-int Put the white space before or behind the*or no spaces int*is a co

5、mpound type double*,float*,char*Pointer Danger A confusion for beginners Creating a pointer in C+means the computer allocates memory to hold an addressaddress BUT it does not does not allocate memory to hold the datadataint*ptr;/create a pointer-to-int:may be NULLNULL,may not*ptr=223323;/place a val

6、ue in never-never land:disasterdisaster Program example init.cppPointers and Numbers Similarities and differences between pointer and integer They are both integersintegersbut pointers are not the integer typetype Both are numbers you can add and subtract but it doesnt make sense to multiply and div

7、ide two locations Why we need addition and subtraction operations?Cant simply assign an integer to a pointer You can do like this:0 xB8000000 is an address literal(hexadecimal)int*ptr=(int*)0 xB8000000;Danger!Pointers and Numbers Size of a pointer:How many bytes used to store a pointer/address?The o

8、utput of the following code?Allocate MemoryC StyleAllocating Memory with malloc()void*malloc(size_t size);Whats size_t?size_t is the unsigned integer type of the result of the sizeof operator size_t can store the maximum size of a theoretically possible object of any type(including array).Allocating

9、 Memory with malloc()DONT forget to free the memeory!void free(void*ptr);The address of ptr will NOT be NULL(0)after you free the memory.Program example malloc.cppHow it worksint*ptr=0;0123456789101112131415ptr=(int*)malloc(16);ptr0 0 0 0A0 CD EF 89 ptr2=0 x0A0B0C0D;0D 0C 0B 0A Allocate MemoryC+Styl

10、eThe slides are based on the book Allocating Memory with new In C+,we use newTell new for what data type you want memoryLet new find a block of the correct sizeReturn the address of the blockAssign this address to a pointerThis is an example:int*ptr_int=new int;*ptr_int=1;Program example use_new.cpp

11、 Operation:sizeofFreeing Memory with delete delete operator enables you to return memory to the memory pool The memory can then be reusedby other parts of the program Balance the uses of new and delete Memory leakmemory has been allocated but no longer being used Beware of Cannot free a block of mem

12、ory that you have previously freed Cannot use delete to free memory created by ordinary variableUsing new to Create Dynamic Arrays Use new with larger chunks of data,such as arrays,strings,and structuresStatic binding:the array is built into the program at compile timeDynamic binding:the array is cr

13、eated during runtime The size of block can be confirmed during runtime Dont use delete to free memory that new didnt allocate Dont use delete to free the same block of memory twice in succession Use delete if you used new to allocate an array Use delete(no brackets)if you used new to allocate a sing

14、le entity Its safe to apply delete to the null pointer(nothing happens)Using a Dynamic Array How do you use the dynamic array?Identify every element in the blockAccess one of these elementsYou can increase a pointer with+1(or+,or+n)A pointer points to the first elementdouble*p3=new double 3;/space f

15、or 3 doublesp3=p3+1;/increment the pointerp3=p3-1;/point back to beginning Program example arraynew.cppPointers,Arrays,and Pointer Arithmetic Adding one to a pointer variable increases its value by the numbernumberof bytes of the typetypeto which it points Program example addpntrs.cppYou can use poi

16、nter names and array names in the same wayDifferences between themYou can change the value of a pointer,whereas an array name is a constantconstantApplying the sizeof operator to an array name yields the size of the array,but applying sizeof to a pointer yields the size of the pointerUsing new to Cr

17、eate Dynamic Structures Dynamic means the memory is allocated during runtime Creating the structure Accessing its members The arrow membership operator(-)of a hyphen and then a greater-than symbol Program example newstrct.cpp(single element)An Example of Using new and delete for Functions Program ex

18、ample delete.cpp Return the address of the string copy Its usually not a good idea to put new and delete in separate functionsManaging memory for dataThe slides are based on the book Automatic Storage Automatic Storage Ordinary variables defined inside a function use automatic storage and are called

19、 automatic variables They expire when the function terminates Automatic variables typically are stored on a stackstack A last-in,first-out,or LIFO,processStatic Storage Static Storage Static storage is storage that exists throughout the execution of an entire program Two ways Define it externally,ou

20、tside a function Use the keyword static when declaring a variablestatic double fee=56.50;Dynamic Storage Dynamic Storage The new and delete operators provide a more flexible approach than automatic and static variables Refer to as the free store or heap Lifetime of the data is not tied arbitrarily t

21、o the life of the program or the life of a functionCombinations of Types Combinations Include arrays,structures,and pointers Program example mixtypes.cpp:array of structures const event*arp3=&s01,&s02,&s03;const event*ppa=arp;Array Alternatives The vector Template ClassIt is a dynamicdynamicarray(Si

22、milar to the stringclass)Use newand deleteto manage memoryThe vectoridentifier is part of the stdnamespace The array Template ClassThe arrayidentifier is part of the stdnamespaceThe number of elements cant be a variableStaticStaticmemory allocation See Program Example choice.cppComparing Arrays,VectorObjects,and ArrayObjects

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 大学资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁