< previous page page_137 next page >

Page 137
Storing the Address in a Pointer.
Every variable has an address. Even without knowing the specific address of a given variable, you can store that address in a pointer.
For example, suppose that howOld is an integer. To declare a pointer called pAge to hold its address, you would write
int *pAge = 0;
This declares pAge to be a pointer to int. That is, pAge is declared to hold the address of an int.
Note that pAge is a variable like any of the variables. When you declare an integer variable (of type int), it is set up to hold an integer. When you declare a pointer variable like pAge, it is set up to hold an address. A pointer is just a special type of variable that is set up to hold the address of some object in memory; in this case, pAge is holding the address of an integer variable.
In this example, pAge is initialized to 0. A pointer whose value is 0 is called a null pointer. All pointers, when they are created, should be initialized to something. If you don't know what you want to assign to the pointer, assign 0. A pointer that is not initialized is called a wild pointer. Wild pointers are very dangerous.
Note: Practice safe computing: Initialize your pointers!

If you do initialize the pointer to 0, you must specifically assign the address of howOld to pAge. Here's an example that shows how to do that:
int howOld = 50;     // make a variable
int * pAge = 0;      // make a pointer
pAge = &howOld;                      // put howOld's address in pAge
The first line creates a variablehowOld, whose type is unsigned short intand initializes it with the value 50. The second line declares pAge to be a pointer to type unsigned short int and initializes it to 0. You know that pAge is a pointer because of the asterisk (*) after the variable type and before the variable name.
The third and final line assigns the address of howOld to the pointer pAge. You can tell that the address of howOld is being assigned because of the address of operator (&). If the address of operator were not used, the value of howOld would be assigned. That mightor might notbe a valid address.

 
< previous page page_137 next page >

If you like this book, buy it!