Sams Teach Yourself C++ in 21 Days

(singke) #1
assigns an address for it. For a longinteger that is typically four bytes, for example, an
address to four bytes of memory is used.

224 Day 8


Note that your compiler might insist on assigning new variables on four-byte
boundaries. (Thus, longVarwas assigned an address four bytes after
shortVareven though shortVaronly needed two bytes!)

NOTE

Storing a Variable’s Address in a Pointer ......................................................


Every variable has an address. Even without knowing the specific address, you can store
a variable’s address in a pointer.
Suppose, for example, that howOldis an integer. To declare a pointer called pAgeto hold
its address, you write
int *pAge = 0;
This declares pAgeto be a pointer to an int. That is,pAgeis declared to hold the address
of an integer.
Note that pAgeis a variable. When you declare an integer variable (type int), the com-
piler sets aside enough memory to hold an integer. When you declare a pointer variable
such as pAge, the compiler sets aside enough memory to hold an address (on most com-
puters, four bytes). A pointer, and thus pAge, is just a different type of variable.

Pointer Names ................................................................................................


Because pointers are just another variable, you can use any name that is legal for other
variables. The same naming rules and suggestions apply. Many programmers follow the
convention of naming all pointers with an initial p, as in pAgeor pNumber.
In the example,
int *pAge = 0;
pAgeis initialized to zero. A pointer whose value is zero is called a nullpointer. 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 wildpointer because you have no idea what it is pointing to—and it could be pointing
to anything! Wild pointers are very dangerous.
Free download pdf