Home PageCourse Selections

Regular Session         

Summer Session

Clubs

Calendar

ContestsRelated TopicsLibrary

The Site

C++ Pointers

Example 1

 

 

#include <iostream>

using namespace std;

 

int main()

{

     int  num = 5;                 //the variable num stores an integer, 5

     int  *where;                   // where is a pointer, stores an address

    where = &num;             // where now stores the address of num

    cout << "The address stored in where = " << where << endl;

    cout << "The contents of *where = " << *where << endl;

     return 0;

}

 
  Run output (the address is machine-dependent):

 

 
 
  The declaration  int  *where  implements a pointer variable.  The statement  where =
     &num  assigns the address of num to the pointer variable where.  The address stored in
     where is machine-dependent.
 
  The (*) operator is called the dereferencing operator.  This unary operator returns the
     contents of the address it is applied to.  The effect of  *where  is to return the contents
     of address a7b2.  Another way to translate  *where  is to think of it as *(a7b2).  The
     first cout statement prints out the address stored in where, address a7b2.  The second
     cout statement prints out the contents of *where, which is 5.
 
  Notice that the (*) operator is used in two different ways in this program.  When it is
     part of a variable declaration (int  *where) it is seting up a pointer variable.  When it
     is used as part of a statement, (*where) it is dereferencing a memory address.
 
  A pointer variable can point to no address.  This is accomplished in one of two ways. 
   
     Assume a is a pointer variable.
 
    a = 0;
    a = NULL;
 
    In either case, the pointer variable a is holding no address.