|
|
|
|
|
|
|
At this point, pAge has as its value the address of howOld. howOld, in turn, has the value 50. You could have accomplished this with fewer steps, as in |
|
|
|
|
|
|
|
|
unsigned short int howOld = 50; // make a variable
unsigned short int * pAge = &howOld; // make pointer to howOld |
|
|
|
|
|
|
|
|
pAge is a pointer that now contains the address of the howOld variable. Using pAge, you can actually determine the value of howOld, which in this case is 50. Accessing howOld by using the pointer pAge is called indirection because you are indirectly accessing howOld by means of pAge. Later today you will see how to use indirection to access a variable's value. |
|
|
|
|
|
|
|
|
Indirection means accessing the value at the address held by a pointer. The pointer provides an indirect way to get the value held at that address. |
|
|
|
|
|
|
|
|
Pointers can have any name that is legal for other variables. This book follows the convention of naming all pointers with an initial p, as in pAge and pNumber. |
|
|
|
|
|
|
|
|
The indirection operator (*) is also called the dereference operator. When a pointer is dereferenced, the value at the address stored by the pointer is retrieved. |
|
|
|
|
|
|
|
|
Normal variables provide direct access to their own values. If you create a new variable of type unsignedshort int called yourAge, and you want to assign the value in howOld to that new variable, you would write |
|
|
|
|
|
|
|
|
unsigned short int yourAge;
yourAge = howOld; |
|
|
|
|
|
|
|
|
A pointer provides indirect access to the value of the variable whose address it stores. To assign the value in howOld to the new variable yourAge by way of the pointer pAge, you would write |
|
|
|
|
|
|
|
|
unsigned short int yourAge;
yourAge = *pAge; |
|
|
|
|
|
|
|
|
The indirection operator (*) in front of the variable pAge means the value stored at. This assignment says, Take the value stored at the address in pAge and assign it to yourAge. |
|
|
|
|
|
|
|
|
The indirection operator (*) is used in two distinct ways with pointers: declaration and dereference. When a pointer is declared, the star indicates that it is a pointer, not a normal variable. For example: |
|
|
|
|
|
|