21.1.  Pointer Pathology

[ fromfile: ptrpathology.xml id: ptrpathology ]

Example 21.1. src/pointers/pathology/pathologydecls1.cpp

[ . . . . ]

int main() {
    int a, b, c;  1
    int* d, e, f; 2
    int *g, *h;   3
    int* i, * j;  4

    return 0;
}

1

As expected, this line creates three ints.

2

This line creates one pointer to an int and two ints. (!)

3

This line creates two pointers to int.

4

This line also creates two pointers to int.


Example 21.2. src/pointers/pathology/pathologydecls2.cpp

[ . . . . ]
int main() {
    int myint = 5;
    int* ptr1 = &myint;
    cout << "*ptr1 = " << *ptr1 << endl;
    int anotherint = 6;
//  *ptr1 = &anotherint;   1
    
    int* ptr2;             2
    cout << "*ptr2 = " << *ptr2 << endl;
    *ptr2 = anotherint;    3

    int yetanotherint = 7;
    int* ptr3;
    ptr3 = &yetanotherint; 4
    cout << "*ptr3 = " << *ptr3 << endl;
    *ptr1 = *ptr2;         5
    cout << "*ptr1 = " << *ptr1 << endl;

    return 0;
}
[ . . . . ]

1

Error, invalid conversion from int* to int.

2

Uninitialized pointer.

3

Unpredictable results.

4

Regular assignment.

5

Dangerous assignment!