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

 


Pointers arithmetic

  • increment a pointer ( ++ )
  • decrement a pointer ( -- )
  • Address in pointer is incremented or decremented by the size of the object it points to (char = 1 byte, int = 2 bytes, ...)

Example:

char         x = 'A', 
             z = 'B';      // variable declaration and initialization
int          y = 32;
char         *xPtr = &x,
             *yPtr = &y,
             *zPtr = &x;   // pointer declaration and initialization 

...
xPtr--;     // Since char takes 1 byte, and xPtr has a value of 108
            // now it has a value of address 107  
xPtr++;     // pointer has a value of address 108 

 

  • add to a pointer (+=)
  • subtract from a pointer (-=)
  • Value added or subtracted from pointer is first multiplied by size of object it points to

Example:

...
yPtr-=3;     // Since int takes 2 byte, and yPtr was pointing to
            // address of 109, now it points to address of 103 
            // 109 - (3 * 2) = 103  
yPtr+=1;     // now yPtr points to address of 105

 

  • pointers comparison (>, <, ==)

Example:

...
if (xPtr == zPtr)

    cout << "Pointers point to the same location";

else

    cout << "Pointers point to different locations";