We can say the pointer as a variable which holds the memory address of another variable. If one variable contains the address of another variable, the first variable is said to point to the second.

Declaring a Pointer

If a variable is holding the address of another variable then we can declare it as

Here var_type is the valid C++ Language data type and varName is the name of the pointer variable. The type of a variable defines that which variable type a pointer can hold.

There are two types of pointer operators; * and &. the & is a unary operator that returns the memory address of its operand. e.g.

vvarName = &newVar;

The * operator is the compliment of the & operator. It returns the value of the variable located at the address thta follows. e.g.

Pointer Example

Examine the program named POINTERS.CPP for a simple example of the use of pointers.

This is a pointer review and if you are comfortable with the use of pointers, you can skip this example program completely. A pointer in either ANSI-C or C++ is declared with an asterisk preceding the variable name. The pointer is then a pointer to a variable of that one specific type and should not be used with variables of other types. Thus pt_int is a pointer to an integer type variable and should not be used with any other type. Of course, an experienced C programmer knows that it is simple to coerce the pointer to be used with some other type by using a cast, but he must assume the responsibility for its correct usage.

In line 12 the pointer named pt_int is assigned the address of the variable named pig and line 13 uses the pointer named pt_int to add the value of dog to the value of pig because the asterisk dereferences the pointer in exactly the same manner as standard C. The address is used to print out the value of the variable pig in line 14 illustrating the use of a pointer with the stream output operator cout. Likewise, the pointer to float named pt_float is assigned the address of x, then used in a trivial calculation in line 18.

If you are not completely comfortable with this trivial program using pointers, you should review the use of pointers in any good C programming book or Coronado Enterprises C tutorial before proceeding on because we will assume that you have a thorough knowledge of pointers throughout the remainder of this tutorial. It is not possible to write a C program of any significant size or complexity without the use of pointers.