C++ Pointers

A pointer is a derived data type; thai is, it is a data type built from one of the standard types. Pointers are what they sound like…pointers. They point to locations in memory. They give both the memory location and the actual value stored in that location.

When a pointer is declared, the syntax is: return_type *pointer_name; Notice the *. This is the key to declaring a pointer; if you use it before the variable name, it will declare the variable to be a pointer.

In order to have a pointer actually point to another variable, it is necessary to have the memory address of that variable as well. To get the memory address of the variable, put the & sign in front of the variable name. Doing this gives the address. This is called the reference operator, because it returns the memory address.

Here is a sample program to demonstrate this:

#include <iostream>
using namespace std;
int main()
{
   int x = 5;
   int *pointer;
   pointer = &x;    // &x refers to the memory address of x 
   cout << "x = " << x << endl;
   cout << "pointer = " << pointer << endl;
   cout << "*pointer = " << *pointer << endl;
}
// end program

When compiled, the program will have the following output:

x = 5
pointer = 70043573
*pointer = 5

The diagram shown below will point out why we get these results.

We see the variable x, with its value, 5. The variable x is found at location 70043573 in memory. This value is just a random memory location, and will change every time the program is executed. The variable pointer contains the memory location 70043573. This refers to the address of variable x (&x). The arrow shows that pointer is pointing to where the variable x is located. To retrieve the data contained in x using pointers, we simply use the variable *pointer, which refers to the integer found in memory address 70043573.

One of the most useful applications of pointers is in functions. In C++, there are two ways to pass parameters to functions: pass by value and pass by reference.

Let's look at some functions to help explain the difference between these ways:

In this example, we have a reference to the variables in the called function. This allows C++ to pass the address of the parameter variables, creating an alias for the variables. Thus, a and b will be exchanged.


This page has been accessed     times.
Last modified: Sunday, 25-Mar-2012 17:31:14 CST
Copyright 2000 Department of Computer Science, University of Regina.


 CS Dept Home Page

Teaching Material