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 remainder of today’s lesson focuses on managing data on the free store and access-
ing class member data and functions. Tomorrow, you will learn about passing variables
using pointers, which is called passing by reference.
The Stack and the Free Store (Heap) ..................................................................
In the section “How Functions Work—A Peek Under the Hood” on Day 5, “Organizing
into Functions,” five areas of memory are mentioned:
- Global namespace
- The free store
- Registers
- Code space
- The stack
232 Day 8
unsigned short int * pPointer = 0;
To assign or initialize a pointer, prepend the name of the variable whose address is being
assigned with the address-of operator (&). For example,
unsigned short int theVariable = 5;
unsigned short int * pPointer = &theVariable;
To dereference a pointer, prepend the pointer name with the dereference operator (*).
For example:
unsigned short int theValue = *pPointer