1.1.   Pointers

Pointers are without a doubt one of the most important—and troublesome—aspects of C++. In fact, a large measure of C++’s power is derived from pointers. For example, they allow C++ to support such things as linked lists and dynamic memory allocation. They also provide one means by which a function can alter the contents of an argument. However, these and other uses of pointers will be discussed in subsequent chapters. In this chapter, you will learn the basics about pointers, see how to manipulate them, and discover how to avoid some potential troubles. In a few places in this chapter, it is necessary to refer to the size of several of C++’s basic data types. For the sake of discussion, assume that characters are one byte in length, integers are four bytes long, floats are four bytes long, and doubles have a length of eight bytes. Thus, we will be assuming a typical 32-bit environment.

1.2.What Are Pointers?

A pointer is a variable that contains a memory address. Very often this address is the location of another variable. For example, if x contains the address of y, then x is said to "point to" y. Pointer variables must be declared as such. The general form of a pointer variable declaration is
type *var-name;
Here, type is the pointer’s base type; it must be a valid C++ type. var-name is the name of the pointer variable. For example, to declare p to be a pointer to an integer, use this declaration:

int *p;
For a float pointer, use
float *p;
In general, in a declaration statement, preceding a variable name with an * causes that variable to become a pointer. The type of data that a pointer will point to is determined by its base type. Here is an example:
int *ip; // pointer to integers
double *dp; // pointer to doubles
As the comments indicate, ip is a pointer to integers because its base type is int, and dp is a pointer to doubles because its base type is double. As you will see, the base type is very important in pointer operations.
Share on Google Plus