pointer math

Basic Pointer

Pointer is an address, the location of what we're pointing to.

void pointerBasic() {

    int x=3;

    cout << "x=" << x << '\t' << "&x=" << &x << endl;

    int *y = new int(5);

    cout << "y=" << y << '\t' << "&y=" << &y << "\t*y=" << *y << endl;

    // y is not int, y is a pointer (i.e. address), y has an address too

Array name is also a pointer.  It is the starting address of the array.  However, array name can not be changed.  In other words, it is a "constant pointer".

    int A[5] = {10,20,30,40,50};    // static array with initialization

    cout << "A=" << A << " &A=" << &A << " *A=" << *A << endl;

    cout << "A0=" << A[0] << endl;

Instructions A++ or ++A will generate a compiler error because A is "constant".  It can not be changed.

    cout << "A+1=" << A+1 << '\t' << "*(A+1)=" << *(A+1) << '\t' << "*A+1=" << *A+1 << endl;

    // note pointer+1 is actually increment by 4 (the sizeof int), so the meaning is increment by one element.

    // A+2 is the same A[2], points to the 2nd element

Pointer Math, dangling pointer

void pointerMath(){

    int *p = new int[5];    // how does p differ from y above? int *y = new int(5);

    cout << "p=" << p << " &p=" << &p << endl;

    int *tp = p;

    for (int i=1; i<=5; tp++, i++)

        *tp=(i)*111;

    // pointer math is element based, sizeof(element)

    int x=3;

    x = *(--tp);

    x= *(p+2);

    tp = p;  // two pointers to one object

    delete(p);

    x=*tp;    // dangling pointer is dangerous

}