Trace: pointer

Cpp/Pointer

This is an old revision of the document!


Cpp/Pointer


Traditionally, C programmers have used this form:

int *ptr;

This accentuates the idea that the combination *ptr is a type int value.

Many C++ programmers, on the other hand, use this form:

int* ptr;

This emphasizes the idea that int* is a type, pointer-to-int

main.cpp
// pointer.cpp -- our first pointer variable
#include <iostream>
int main() {
    using namespace std;
    int updates = 6;        // declare a variable
    int * p_updates;        // declare pointer to an int
    // updates = * p_updates; <- value
    // &updates = p_updates; <- address
    p_updates = &updates;   // assign address of int to pointer
 
    // express values two ways
    cout << "Calues: updates = " << updates;
    cout << ", *p_updates = " << *p_updates << endl;
 
    // express address two ways
    cout << "Addresses: &updates = " << &updates;
    cout << ", p_updates = " << p_updates << endl;
 
    // use pointer to change value
    *p_updates = *p_updates + 1;
    cout << "Now updates = " << updates << endl;
 
    return 0;
}

Pointer Golden Rule: Always initialize a pointer to a definite and appropriate address before you apply the dereferencing operator ( * ) to it.