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

 


The relationship between pointers and arrays

int scores[5] = {10, 20, 30, 40, 50};

int *sPtr ;

sPtr = scores;

  • array name (without a subscript) is a pointer to the first element of the array
            *scores     equals      scores[0]
  • because array name is a pointer to the array, another pointer can point to the array as well
...  
sPtr = scores;     // name scores is a pointer to the array 
...     
  • array elements can alernatively be referenced either with the pointer expression or with the array variable.
...
cout << *sPtr             // output 10 
     << sPtr[0]           // outout 10
     << *(sPtr + 1)       // output 20
     << sPtr[1]           // output 20
     << scores[1];        // output 20 
  • incrementing pointer addresses next array element
  • decrementing pointer addresses previoys array element
...  
sPtr = scores[3]; // sPtr points to scores[3] position 
sPtr++;           // now sPtr points to scores[4] position


sPtr = scores[3]; // sPtr points to scores[3] position 
sPtr--;           // now sPtr points to scores[2] position
...