Return to Topic Menu | Computer Science Main Page | | Terms of Use | Resource CD


Pointer Basics

The de-reference operator ( * ) is also called an indirection operator.  Indirection means accessing the value at the address held by the pointer.  The pointer provides an indirect way to read the value held at that address.

Pointers can offer a highly efficient means of accessing and changing data.  Since pointers contain the actual address of the data, the compiler does less work when finding that data in memory.

Naming and Initializing Pointers:

Pointers can have any name that is legal for other variables. Many programmers follow the convention of naming all pointers with an initial p, as in pCount or pNumber

int Count = 10;    // declare and initialize a regular int variable
int *pCount = 0; // declare and initialize an integer pointer

All are the same:
int* pCount = 0;
int *pCount = 0;
int * pCount = 0;

All pointers, when they are created, should be initialized to some value, even if it is only zero.  A pointer whose value is zero is called a null pointer

Practice safe programming:
  Initialize your pointers!


If the pointer is initialized to zero, you must specifically assign the address to the pointer.
                   pCount = &Count; // assign the address to the pointer (NO * is present)

It is also possible to assign the address at the time of declaration.
                  int *pCount = &Count;  //declare and assign an integer pointer

cout<< Count;     //prints 10
cout<< pCount;  // prints 0x8f4dff4, or the current address of count
cout<< *pCount; // prints 10

The * appears before the pointer variable in only TWO places:
1. when you declare a pointer variable, and
2. when you de-reference a pointer variable (point to (access) the data whose address is stored in the pointer)

It is important to distinguish between
a pointer,
the address that the pointer holds, and 
the value at the address held by the pointer.

//Example - variable of type pointer
#include <iostream.h>

int main(void)
     char first = 'A';
     char second = 'B';
     char *p = &first;

     cout<< *p << endl;  // dereference - output A
     p = &second;
     cout<< *p <<endl;   //dereference - output B

     p = &first;
     *p = 'Z';     
            // set first to 'Z'
p = &second;
     *p = 'Y';

     cout << first << second <<endl;   // output ZY

     return 0;