C++ Notes to Self: Pointers

C/C++
‘Pointers are a very powerful feature of the language that has many uses in lower level programming.’ [cplusplus.com]
Author

Dennis Chua

Published

February 13, 2017


A pointer points to another type. A pointer variable holds the memory address of another variable and is used to access that other variable indirectly. C++ doesn’t require pointer initialization during declaration, but providing pointer initialization is good practice. An uninitialized pointer contains random memory address.

The pointer is declared with the same type of variable that it points to. In some cases we need a pointer that points to varying types. Here the void pointer comes in handy.

In C and pre-C++11, a null pointer is a macro often defined as 0x00. C++11 introduces a new type of pointer called nullptr that is type safe and beter than the null macro. Note that you can not read a pointer assigned to nullptr. During runtime C++ will throw an access violation exception. In the same way, you can not write to a pointer assigned to a nullptr memory. This will lead to write acess violations.

#include <iostream>

using namespace std;

int main(int argc, char **argv) {

    int x = 10;
    cout << &x << endl; // Display the memory address of variable x
    
    int *ptr = &x; // Memory address operator (&) and dereference operator (*)

    cout << ptr << endl; // Also displays the same memory address now held by ptr

    int *ptr1 = &x;     
    *ptr1 = 222; // Variable x is updated by means of pointer ptr
    cout << *ptr1 << endl;

    ptr1 = nullptr;

    return 0;
}