Sams Teach Yourself C++ in 21 Days

(singke) #1

226 Day 8


The type tells the compiler how much memory is needed for the object at
the address, which the pointer holds!
In the declaration
unsigned short int * pAge = 0; // make a pointer
pAgeis declared to be a pointer to an unsigned shortinteger. This tells the
compiler that the pointer (which needs four bytes to hold an address) will
hold the address of an object of type unsigned short int, which itself
requires two bytes.

Dereferencing with the Indirection Operator ................................................


The indirection operator (*) is also called the dereferenceoperator. 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 unsigned short intcalled yourAge, and you want to assign the value in howOld
to that new variable, you write
unsigned short int yourAge;
yourAge = howOld;
A pointer provides indirectaccess to the value of the variable whose address it stores. To
assign the value in howOldto the new variable yourAgeby way of the pointer pAge, you
write
unsigned short int yourAge;
yourAge = *pAge;
The indirection operator (*) in front of the pointer variable pAgemeans “the value
stored at.” This assignment says, “Take the value stored at the address in pAgeand
assign it to yourAge.” If you didn’t include the indirection operator:
yourAge = pAge; // bad!!
you would be attempting to assign the value in pAge, a memory address, to YourAge.
Your compiler would most likely give you a warning that you are making a mistake.

Different Uses of the Asterisk
The asterisk (*) is used in two distinct ways with pointers: as part of the pointer declara-
tion and also as the dereference operator.
When you declare a pointer, the *is part of the declaration and it follows the type of the
object pointed to. For example,
Free download pdf