|
This material concerns the concept and use of pointers. The subject seems to be difficult for neophyte programmers. Perhaps a grounding in assembly language, where one deals routinely with immediate, direct, and indirect references, was a help to many of us old salts. I hope to demystify the subject enough to prevent beginning users from falling into the most common traps. In honor of the subject, the navigational icon has been provided with a small surplus. |
Pointers
A pointer is a programming language datatype whose value is used to refer to ("points to") another value stored elsewhere in the computer memory. It is not a "reference type" in the strict sense used in C++, but it does refer to another variable or other object. The dictionary definition is sufficient here. In that context the name of a variable, its address, and any terms of endearment your spouse or lover use also qualify.
A pointer is like a name in your little black book. It tells you where someone lives. The someone does not live in your address book. If the address does not exist, it's a fool's errand to go there hoping for a date tonight. A pointer must be valid to be useful. It is part of a pair. It's worthless, indeed a hazard, without the mate.
To dereference a pointer is to follow its directions in order to locate the thing it refers to. If that thing doesn’t exist, there may be trouble in River City. Dereferencing an invalid pointer is somewhat like picking a bad address out of your little black book. On your way to a hot date you may step into a hatchet fight and experience a segmentation fault of the worst kind. In the same way, suppose I tell you to point to the person you want to help you dig a ditch. If you point to where no one is standing, you're gonna be down in a hole with a pick all by yourself.
The pointer is not the actual object you are seeking, but a way to locate that object; the address, the pointing finger. You cannot store your sweetheart in your address book; don't even try. You have to use the address specified. Likewise, as a programmer, you may not store your integers and other such objects in a pointer without courting disaster.
