1 / 59

Memory Management

Memory Management. 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.

leigh
Download Presentation

Memory Management

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Memory Management Microsoft Visual C++ .NET Chapter 6

  2. 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 Microsoft Visual C++ .NET Chapter 6

  3. 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 Microsoft Visual C++ .NET Chapter 6

  4. 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 Microsoft Visual C++ .NET Chapter 6

  5. 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 Microsoft Visual C++ .NET Chapter 6

  6. Passing a Pointer to the Currency Array Microsoft Visual C++ .NET Chapter 6

  7. 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 Microsoft Visual C++ .NET Chapter 6

  8. 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 Microsoft Visual C++ .NET Chapter 6

  9. 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 Microsoft Visual C++ .NET Chapter 6

  10. 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 Microsoft Visual C++ .NET Chapter 6

  11. 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 Microsoft Visual C++ .NET Chapter 6

  12. 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 Microsoft Visual C++ .NET Chapter 6

  13. 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 Microsoft Visual C++ .NET Chapter 6

  14. 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 Microsoft Visual C++ .NET Chapter 6

  15. 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 Microsoft Visual C++ .NET Chapter 6

  16. 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 Microsoft Visual C++ .NET Chapter 6

  17. 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 Microsoft Visual C++ .NET Chapter 6

  18. 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 Microsoft Visual C++ .NET Chapter 6

  19. 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 Microsoft Visual C++ .NET Chapter 6

  20. 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 Microsoft Visual C++ .NET Chapter 6

  21. 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 Microsoft Visual C++ .NET Chapter 6

  22. 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 Microsoft Visual C++ .NET Chapter 6

  23. 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 Microsoft Visual C++ .NET Chapter 6

  24. 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 Microsoft Visual C++ .NET Chapter 6

  25. 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 Microsoft Visual C++ .NET Chapter 6

  26. The Name of the arInterestRates[] Array Pointing to the Memory Address of the Array’s First Element Microsoft Visual C++ .NET Chapter 6

  27. 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 Microsoft Visual C++ .NET Chapter 6

  28. 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 Microsoft Visual C++ .NET Chapter 6

  29. 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 Microsoft Visual C++ .NET Chapter 6

  30. 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 Microsoft Visual C++ .NET Chapter 6

  31. Pointer Arithmetic • Figure 6-36 illustrates the process of using pointer arithmetic to increase the pCurInterestRate pointer by one Microsoft Visual C++ .NET Chapter 6

  32. 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 Microsoft Visual C++ .NET Chapter 6

  33. Multidimensional Arrays Microsoft Visual C++ .NET Chapter 6

  34. 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 Microsoft Visual C++ .NET Chapter 6

  35. 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 Microsoft Visual C++ .NET Chapter 6

  36. 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 Microsoft Visual C++ .NET Chapter 6

  37. 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 Microsoft Visual C++ .NET Chapter 6

  38. 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 Microsoft Visual C++ .NET Chapter 6

  39. 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 Microsoft Visual C++ .NET Chapter 6

  40. 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 Microsoft Visual C++ .NET Chapter 6

  41. 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 Microsoft Visual C++ .NET Chapter 6

  42. Multidimensional arDepartments[] Array Microsoft Visual C++ .NET Chapter 6

  43. 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 Microsoft Visual C++ .NET Chapter 6

  44. 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 Microsoft Visual C++ .NET Chapter 6

  45. Memory Spaces Occupied by the arDepts[] Array Microsoft Visual C++ .NET Chapter 6

  46. 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 Microsoft Visual C++ .NET Chapter 6

  47. 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 Microsoft Visual C++ .NET Chapter 6

  48. 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 Microsoft Visual C++ .NET Chapter 6

  49. 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 Microsoft Visual C++ .NET Chapter 6

  50. 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 Microsoft Visual C++ .NET Chapter 6

More Related