Download presentation
Presentation is loading. Please wait.
Published byElijah Harold Bradley Modified over 9 years ago
1
Microsoft Visual C++.NET Chapter 61 Memory Management
2
Microsoft Visual C++.NET Chapter 62 Objectives In this chapter you will learn: How to work with pointers How to work with references How to use pointers and references with functions How to work with pointers and references to objects About advanced array techniques How to dynamically allocate memory
3
Microsoft Visual C++.NET Chapter 63 Pointers A pointer is a special type of variable that stores the memory address of another variable You use pointers to manipulate a variable and its contents through its memory address instead of through its variable name Working with pointers confers many advantages, all related to the efficiency of your programs But the most important advantage comes when you need to use functions to work with or modify large variables, such as an object or complex array
4
Microsoft Visual C++.NET Chapter 64 Pointers As an example of a large variable, consider the currency conversion table shown in Figure 6-7 As you know, you can pass primitive data types, such as double or int, to a function
5
Microsoft Visual C++.NET Chapter 65 Pointers You can also pass an object or an array to a function However, when you pass an array to a function, you are really passing a pointer to the array Passing just a pointer to an array saves a significant amount of memory over passing a copy of the array This concept of passing a pointer to an array is illustrated in Figure 6-8
6
Microsoft Visual C++.NET Chapter 66 Passing a Pointer to the Currency Array
7
Microsoft Visual C++.NET Chapter 67 Declaring and Initializing a Pointer You declare a pointer with a data type, just as you declare ordinary variables To declare a variable as a pointer, you place the indirection operator (*) after the data type or before the variable name The indirection operator gets its name because a pointer variable indirectly accesses a value through its memory address, whereas a regular variable directly accesses a stored value
8
Microsoft Visual C++.NET Chapter 68 Declaring and Initializing a Pointer After you declare a pointer variable, you use the address of (&) operator to assign to the pointer variable the memory address of another variable You place the address of the operator in front of the variable whose address you want to assign to the pointer To start building the showOrders() function, use the steps on page 291 of the textbook
9
Microsoft Visual C++.NET Chapter 69 De-Referencing a Pointer Once you assign the memory address of a variable to a pointer, to access or modify the contents of the variable pointed to by the pointer, you precede a pointer name in an expression with the de-reference (*) operator The de-reference operator (*) happens to be an asterisk, the same as the indirection operator You can distinguish the two operator types by the fact that the indirection operator is used only when declaring a pointer, whereas the de-reference operator is used to access or modify the contents of the address pointed to by a pointer
10
Microsoft Visual C++.NET Chapter 610 References A reference, or reference variable, is an alias for an existing variable Compared to pointer variables, references provide a streamlined way to pass large variables to and return large variables from a function
11
Microsoft Visual C++.NET Chapter 611 Declaring and Initializing a Reference You create a reference by appending the address of operator (&) to the data type in a variable declaration and assigning an existing variable to the new variable name The syntax for creating a reference is data type& reference_name = variable_name; Once you create a reference, you can use it exactly as you would use a standard variable
12
Microsoft Visual C++.NET Chapter 612 Declaring and Initializing a Reference You do not need to use any special operators to access or modify the original variable as you do with pointers Refer to the code illustrated at the top of page 295 of the textbook
13
Microsoft Visual C++.NET Chapter 613 References Compared to Pointers A pointer stores the memory address of a variable, whereas a reference is an alias for a variable In reality, a reference also stores the memory address of a variable, but it behaves like a variable A reference can be easier to work with than a pointer because you do not have to use special operators to access the variable for which the reference is an alias
14
Microsoft Visual C++.NET Chapter 614 References Compared to Pointers One of the most common times that a reference is used is when you need one function to work with a large variable that is declared in another function One important reason why you would need to use a pointer instead of a reference is that a reference variable cannot be reassigned
15
Microsoft Visual C++.NET Chapter 615 Using Pointers and References with Functions One of the most important reasons for working with pointers and references is to minimize the amount of memory required when passing arguments to a function There are three primary methods of passing arguments to a function: call-by-value, call- by-address, and call-by-reference
16
Microsoft Visual C++.NET Chapter 616 Call-by-Value Passing a variable to a function is referred to as calling-by-value or passing-by-value because only the value of the variable is passed to the function instead of the variable itself The important thing to remember when you pass a variable to a function by value is that the called function receives a duplicate of the value passed to it Any change the called function makes to the duplicate value is not reflected in the original variable
17
Microsoft Visual C++.NET Chapter 617 Call-by-Address Calling-by-value is most efficient for small variables of primitive data types, such as an int or double variable However, for large objects, a more efficient method is to pass only the memory address of the variable, using a pointer variable Passing a pointer to a function is referred to as calling-by-address or passing-by-address because only the memory address of the variable is passed to the function instead of the value of the variable
18
Microsoft Visual C++.NET Chapter 618 Call-by-Reference Passing a reference variable to a function is referred to as calling-by-reference or passing-by-reference because only a reference is passed to the function instead of the vale itself Just as with pointers, a function can manipulate an original variable through a passed reference, avoiding the costly memory overhead required by passing a large variable to, and returning a large variable from, a function The definition for a function you want to call-by- reference must declare a reference parameter of the object type you want to pass
19
Microsoft Visual C++.NET Chapter 619 Call-by-Reference The original modifyOrder(curOrder); statement you added to the showOrders() function passes the FloristOrder object (curOrder) by value Modify the modifyOrder(curOrder); statement in the ShowOrders() function so the FloristOrder object is passed-by- reference by following the processes shown on pages 306 and 307 in the textbook
20
Microsoft Visual C++.NET Chapter 620 Working with Pointers and References to Objects As you know, you use the member selection operator (.) to access class members through an object instance However, to access class members through a pointer to an object, you must use the indirect member selection operator (->) A pointer named pStock is declared for the stockPick object
21
Microsoft Visual C++.NET Chapter 621 The this Pointer When your program calls a member function of a class, the compiler knows which object instance called the function through the this pointer The this pointer identifies the object instance that called a function C++ uses the this pointer to be sure that a member function uses the correct set of data members for a given object By default, the this pointer is implied, meaning that a member function automatically knows that the this pointer points to the calling object
22
Microsoft Visual C++.NET Chapter 622 The this Pointer The code shown on page 311 is an example of the implementation for the Stock class member functions you saw earlier Each data member is referenced using the this pointer with the indirect member selection operator To add this pointers to the FloristOrder class constructor function, use the procedures on pages 311 and 312 in the textbook
23
Microsoft Visual C++.NET Chapter 623 Advanced Array Techniques Each element of an array represents one of the array’s memory locations, and you access each element through its index number The number of elements in an array is referred to as its dimension, and the numbering of elements within an array starts with an index number of 0 Figure 6-28 illustrates how the elements of the arInterestRates[] array are stored in memory using some sample memory addresses
24
Microsoft Visual C++.NET Chapter 624 Advanced Array Techniques To store the flower prices in an array data member, follow the instructions outlined on pages 314 through 316 in the textbook
25
Microsoft Visual C++.NET Chapter 625 Pointers and Arrays An array name is actually a pointer that points to the memory address of the first element in the array The name of the arInterestRates[] array is really a pointer that points to the memory address of the array’s first element, arInterestRates[0], as illustrated in Figure 6- 32
26
Microsoft Visual C++.NET Chapter 626 The Name of the arInterestRates[] Array Pointing to the Memory Address of the Array’s First Element
27
Microsoft Visual C++.NET Chapter 627 Pointers and Arrays You can assign the name of one pointer variable to another, which actually assigns the memory address stored in the right pointer operand to the left pointer operand
28
Microsoft Visual C++.NET Chapter 628 Pointers and Arrays Array names are constant pointers; no change can be made to the value they store after they are declared and initialized To assign to a pointer the memory address where an individual element of an array is stored, you must use the address of (&) operator Be sure to place the appropriate index number in brackets at the end of the array name Practice adding to the Florist Order program an array pointer named pFlowerPrices by using the steps on page 319 of the textbook
29
Microsoft Visual C++.NET Chapter 629 Pointer Arithmetic With pointer arithmetic, you can use addition and subtraction to change the element number that is the target of a pointer The main benefit of pointer arithmetic is that it allows you to easily change the element number that is the target of a pointer Next, you will modify the getPricePerUnit() function in the Florist Order program so that the elements of the arFlowerPrices[] array are accessed using pointer arithmetic
30
Microsoft Visual C++.NET Chapter 630 Pointer Arithmetic Remember that because an array name is a constant pointer, you cannot modify its contents; a memory address of an element pointed to by the array name, such as arInterestRates = pCurInterestRate + 1;, is illegal Be aware that pointer arithmetic does not simply increase the integer that represents the index of an array element Pointer arithmetic changes the memory address being pointed to according to the size of the array’s data type
31
Microsoft Visual C++.NET Chapter 631 Pointer Arithmetic Figure 6-36 illustrates the process of using pointer arithmetic to increase the pCurInterestRate pointer by one
32
Microsoft Visual C++.NET Chapter 632 Multidimensional Arrays You can create multidimensional arrays, which consist of multiple indexes To understand how a multidimensional array works, first consider a one-dimensional array that contains federal tax withholding amounts For the tax year 2001, the IRS assesses a different base tax amount depending on whether you are single, married, married filing jointly, married filing separately, or the head of a household
33
Microsoft Visual C++.NET Chapter 633 Multidimensional Arrays
34
Microsoft Visual C++.NET Chapter 634 Multidimensional Arrays A multidimensional array that contains two indexes is referred to as a two-dimensional array The first index in the declaration of a two- dimensional array determines the number of rows in the array, and the second index determines the number of columns The table in Figure 6-39 shows the index number for the element in the array where each value is stored
35
Microsoft Visual C++.NET Chapter 635 Multidimensional Arrays If you do not want to initialize a multidimensional array at declaration, you can initialize individual elements later by using both indexes with the array name Figure 6-40 in the text shows a simple program that returns a single taxpayer’s federal income tax from the arTaxTable[] array, based on his or her taxable income, and Figure 6-41 shows the output
36
Microsoft Visual C++.NET Chapter 636 Multidimensional Arrays Multidimensional arrays are not limited to two dimensions You can include as many indexes as you need when you declare the array However, the more dimensions you use, the more complex, and more limited in use, the array becomes Figure 6-42 shows how the Alaska table might appear for the first year
37
Microsoft Visual C++.NET Chapter 637 Multidimensional Arrays To initialize a three- dimensional array, you need to include a separate nested initializer list, separated by commas, for each of the rows represented by the first index
38
Microsoft Visual C++.NET Chapter 638 Multidimensional Arrays To add a multidimensional array to the Florist Order program that will store unit prices for each type of flower according to a volume discount, use the procedures outlined on pages 327 through 330 in the textbook
39
Microsoft Visual C++.NET Chapter 639 Character Arrays When you create a char variable using a statement similar to char szString[10];, you are really creating an array of char elements Each character in the string you assign to the char variable is stored in an element of the array You can access the individual elements in a character array the same way that you access elements in arrays of other data types
40
Microsoft Visual C++.NET Chapter 640 Character Arrays Once you create a char* pointer variable, you can use it in much the same way that you use a string class variable Unlike other types of pointers, you do not need to use the address of or de-reference operators to access and modify the contents of a char* pointer variable You also do not need to use any of the functions of the String object in order to modify the contents of a char* pointer after its initial declaration
41
Microsoft Visual C++.NET Chapter 641 Multidimensional Character Arrays When you declare a multidimensional array of strings, the first index in the array declaration determines the number of rows, and the second index determines the maximum number of characters to store To store each of the flower names in a multidimensional character array, perform the procedures shown on pages 333 and 334 in the textbook Also examine the layout of the multidimensional arDepartments[] array in Figure 6-50
42
Microsoft Visual C++.NET Chapter 642 Multidimensional arDepartments[] Array
43
Microsoft Visual C++.NET Chapter 643 Arrays of char* Pointers It is more memory-efficient to store character strings in an array of char* pointers than to store them in a multidimensional array Declaring an array of char* pointers stores only the pointers in the array Each of the stored pointers in turn points to a character array Each char* pointer reserves only enough memory to store the literal string that is passed to it
44
Microsoft Visual C++.NET Chapter 644 Arrays of char* Pointers Figure 6-51 shows an example of the memory spaces occupied by the pointers in the arDepts[] pointers array Figure 6-50 shows only the memory spaces occupied by the character arrays that are pointed to by the pointers stored in the arDepts[] array To modify the arFlowers[] array in the FloristOrder class so that it stores an array of pointers instead of a multidimensional character array, use the steps listed on page 337 of the textbook
45
Microsoft Visual C++.NET Chapter 645 Memory Spaces Occupied by the arDepts[] Array
46
Microsoft Visual C++.NET Chapter 646 Arrays of Objects An array of objects allows you to easily manage objects in your program that are of the same data type When you create an array of primitive data types, you can use an initializer list at declaration to initialize each element, as each element will only contain one piece of data However, with an array of objects, you must declare the array in one statement and then use additional statements to access the class members of each object according to its element number in the array
47
Microsoft Visual C++.NET Chapter 647 Arrays of Objects Refer to the code illustrated on page 338 of the textbook Modify the arFlowers[] array in the FloristOrder class so that it stores an array of string class objects instead of pointers by using the procedures on page 338 of the textbook
48
Microsoft Visual C++.NET Chapter 648 Arrays and Functions An array parameter is a formal parameter that you define as part of a function definition An array argument is an array that you pass to an array parameter in a call to a function The memory address of the first element in the array argument is assigned to the array parameter defined in the function You define an array parameter using a data type and an empty set of brackets ([]) in the prototype and definition for a function that includes an array parameter
49
Microsoft Visual C++.NET Chapter 649 Arrays and Functions The empty set of brackets ([]) in a parameter definition notifies C++ that the parameter is an array parameter Figure 6-52 in the text shows an example of a program that includes the yearEndBonus() function with an array parameter Figure 6-53 shows the output
50
Microsoft Visual C++.NET Chapter 650 Dynamic Memory Allocation The local variables, such as int iCount;, and pointers, such as int* iCount;, you have seen so far are created in an area of memory known as the stack The stack is a region of memory where applications can store data such as local variables, function calls, and parameter information Sometimes you will want to have greater control over the allocation and de-allocation of the memory used by your program
51
Microsoft Visual C++.NET Chapter 651 Dynamic Memory Allocation To allocate variables at run time, you use an area of memory known as the heap The heap, or the free store, is an area of memory that is available to an application for storing data whose existence and size are not known until run time Adding and removing variables with the new and delete keywords at run time is referred to as dynamic memory allocation
52
Microsoft Visual C++.NET Chapter 652 The new Keyword The new keyword creates a variable on the heap and returns a pointer to the variable’s heap memory address Once you allocate a heap variable, you refer to it in your code the same way you refer to other pointer variables Modify the main() function so it dynamically creates an array of FloristOrder objects by using the procedures shown on pages 343 and 344 in the textbook
53
Microsoft Visual C++.NET Chapter 653 The delete Keyword You use the delete keyword to de-allocate memory that has been reserved on the heap The syntax for calling the delete keyword is delete pointer_name; The delete keyword does not delete the pointer itself Rather, it deletes the contents of the heap memory address pointed to by a pointer variable
54
Microsoft Visual C++.NET Chapter 654 The delete Keyword You can reuse the pointer itself after calling the delete keyword If you examine the output in Figure 6-57, you will see that after the delete statement executes, the pPrimeInterest pointer still points to the same memory address
55
Microsoft Visual C++.NET Chapter 655 The delete Keyword If you fail to delete heap variables, your program may experience something called a memory leak A memory leak is a condition in which a system’s memory is not released after it is used (in other words, it “leaks out” of the heap) Add a statement to the Florist Order program that releases the heap memory used by the arFloristObjects array in the main() function by using the steps shown on pages 347 and 348 of the textbook
56
Microsoft Visual C++.NET Chapter 656 Summary A pointer is a special type of variable that stores the memory address of another variable A reference, or reference variable, is an alias for an existing variable Passing a pointer to a function is referred to as calling-by-address or passing-by-address because only the memory address of the variable is passed to the function instead of the value of the variable
57
Microsoft Visual C++.NET Chapter 657 Summary Passing a reference variable to a function is referred to as calling-by-reference or passing-by- reference because only the reference variable is passed to the function instead of the value itself You must use the indirect member selection operator (->) to access class members through a pointer to an object either on the stack or on the heap The this pointer identifies the object instance that called a function
58
Microsoft Visual C++.NET Chapter 658 Summary With pointer arithmetic, you can use addition and subtraction to change the element number that is the target of a pointer Multidimensional arrays consist of multiple indexes An alternate method to declaring the number of elements in a character array using brackets is to use a char* pointer, which automatically allocates the correct number of elements to the character array
59
Microsoft Visual C++.NET Chapter 659 Summary Adding variables to the heap with the new keyword and removing variables from the heap with the delete keyword at run time is referred to as dynamic memory allocation The new keyword creates a variable on the heap and returns the variable’s heap memory address You use the delete keyword to de-allocate memory that has been reserved on the heap
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.