Eroxl's Notes
Pointer

A pointer is a variable which stores a memory address.

Declaring Pointer Variables

C and C++

Pointer variables are defined as follows:

int *ptr;

where int can be any data type and defines the type of value at that pointers address. Additionally ptr is just the name of the variable and can be any valid name.

Pointer Operations

C and C++

Address Operator

The address operator gets the address of an existing variable and is expressed by placing a & before the variable.

Example

int x = 23;
int *p = &x;

The variable p now stores the address of x.

Dereferencing Operator

The Dereferencing operator gets value at an address is expressed by placing a * before the pointer.

int x = 23;
int *p = &x;

*p = 50;
cout << x << endl; // Outputs 50

C++

new Keyword

The new keyword allocates new space on the heap and returns the first address of the allocated space.

int *b = new int;

delete Keyword

int *b = new int;
*b = 2;

delete b;

For arrays allocated on the heap the delete[] keyword can be used

int *b = new int[3]{1, 2, 3};

delete[] b;

The delete keyword releases the memory at the address referenced by the pointer variable passed to it.

Stacking Pointers

Because pointers can "point" to any address in memory we can create pointers to pointers

int x = 5;
int* p = &x;          // Memory address of `x`
int** q = &p;         // Memory address of `p`
int*** r = &q;        // Memory address of `r`

cout << **r << endl;  // Memory address of `x` (value of `p)
cout << **q << endl;  // Value of `x`
cout << ***r << endl; // Value of `x`