Overview

Why use pointers?

What's a pointer?

Declaring pointers

Initializing/Setting pointers

Pointer operators

Pointer arithmetic

Pointers as parameters

Pointers vs. arrays

Array of pointers

Function pointers

 


Pointer operators

  • The &, or address operator, is a unary operator that returns the address of its operand.

Example:

char   x = 'A', z = 'B';  
int    y = 32;
int    *xPtr;   

...
xPtr = &x;
cout << *xPtr;            // displays 'A'
xPtr = &z;                // assigns address of x variable to xPtr pointer
cout << *xPtr;            // displays 'B'

 

  • The *, or indirection/dereferencing operator, returns a synonym, alias, or nickname for the object to which its pointer points. Valid for basic data types.

Example:

char   x = 'A', z = 'B';   
int    y = 32;
int    *xPtr = &x;  
    
...
xPtr  = &x;               // assigns address of x variable to xPtr pointer
cout << *xPtr;            // displays 'A'
*xPtr = 'C'               // indirectly assigns 'C' to variable x
cout << *xPtr;            // displays 'C'

 

  • The -> is used for structures and union members.

Example:

struct Time{
   int second;
   int minute;
   int hour;
};

...
Time breakTime, *goodTime;

goodTime = &breakTime;
goodTime->hour = 3;
cout <<breakTime.hour    // displays 3
     <<goodTime->hour;   // also displays 3