Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use | Resource CD

 

Pointer with Arrays

CAUTION:  In the development of the "ap" classes (apstring, apvector and apmatrix), pointers were used to manipulate data.  Consequently, pointers are not used when working with  apstring, apvector and apmatrix (you would be pointing to a pointer).  The "ap" classes are truly C++ entities that are dealt with by reference.

Pointers work with older style character arrays (not apstrings):
     Remember we said that pointers were incorporated into the C++ language from C, where strings were expressed as character string arrays such as:
                                                     char name[6] = "Wally";

a l l y /0

 

Let's look at an array with three elements:  
                                                   int A[3];

0 2 4
       52       76               87

A[0]

A[1] A[2]
&A[0] &A[1] &A[2] by reference
*A *(A+1) *(A+2) by pointer
Address examples 1000 1002 1004


// De-reference operator *
#include <iostream.h>

int main(void)
{
     int A[3] = {52, 76, 87};
     cout<< (*A)                     // 52  - our mantra at work!
            << (*(A+1))              // 76
            << (*(A+2))              // 87
            << (*A + 1);             // 76
     return 0;
}


How it Works:
· A is the address of an array of int type.  *A gives the value that is located at this address, which is the same as A[0].

· Most people would guess that A+1 means "add one to address A".  However, this is NOT the case. The statement A+1 means "add 2 to address A" (based upon the space required to store the "type" of variable). 

· A+2 means: "add the length of 2 elements"; in other words, 4 (for type int).

· The expressions A[2] and *(A+2) designate the same thing.

Note:

· The parentheses in *(A+1) are needed because of the precedence of operations. 
    ( * has a higher precedence than + ). If you leave out the parentheses:
                                                           *A + 1
it means something completely different, namely:
                                                            (*A) + 1

which means "add 1 to the value at address A".  For this example, the result of this operation will be 53, not 76.