|
|
|
|
|
|
|
Why Would You Use Pointers? |
|
|
|
|
|
|
|
|
So far you've seen step-by-step details of assigning a variable's address to a pointer. In practice, though, you would never do this. After all, why bother with a pointer when you already have a variable with access to that value? The only reason for this kind of pointer manipulation of an automatic variable is to demonstrate how pointers work. Now that you are comfortable with the syntax of pointers, you can put them to good use. Pointers are used, most often, for three tasks: |
|
|
|
|
|
|
|
|
Managing data on the free store |
|
|
|
|
|
|
|
|
Accessing class member data and functions |
|
|
|
|
|
|
|
|
Passing variables by reference to functions |
|
|
|
|
|
|
|
|
The rest of this chapter focuses on managing data on the free store and accessing class member data and functions. In Hour 10, Advanced Pointers, you will learn about passing variables by reference. |
|
|
|
|
|
|
|
|
The Stack and the Free Store. |
|
|
|
|
|
|
|
|
Programmers generally deal with five areas of memory: |
|
|
|
 |
|
|
|
|
Global name space |
|
|
|
 |
|
|
|
|
The free store |
|
|
|
 |
|
|
|
|
Registers |
|
|
|
 |
|
|
|
|
Code space |
|
|
|
 |
|
|
|
|
The stack |
|
|
|
|
|
|
|
|
Local variables are on the stack, along with function parameters. Code is in code space, of course, and global variables are in global name space. The registers are used for internal housekeeping functions, such as keeping track of the top of the stack and the instruction pointer. Just about all remaining memory is given over to the free store, which is sometimes referred to as the heap. |
|
|
|
|
|
|
|
|
The problem with local variables is that they don't persist. When the function returns, the local variables are thrown away. Global variables solve that problem at the cost of unrestricted access throughout the program, which leads to the creation of code that is difficult to understand and maintain. Putting data in the free store solves both of these problems. |
|
|
|
|
|