Pointer Essentials

Here we’ll explore the raw pointer type, a very fundamental part of the C and C++ language. 

Understanding a Pointer

A raw pointer is simply a data type that represents a block of memory that points to another block of memory. Pointer data types are declared using an asterisk (*) and  are commonly initialized or assigned using another pointer, the address-of operator (&), or the new operator.

Pointers are distinct from their non-pointer counterparts; an int *  is a different type than an int .

Given the following code where the pointer is initialized with the address-of operator:

One can visualize the memory like so:

*myIntPtr

0x400710  0x400711 0x400712  0x400713
 0x672030

myInt

0x672030 0x672031 0x672032 0x672033
 8

Common Operators

There are a few operators used with pointers to grab the memory address from a variable and to get the value a pointer is pointing to.
Address-of (&)
An ampersand used outside of declaration is used to retrieve the address of a variable.

Dereference

An asterisk used outside a declaration is used to pull the value from a pointer, as used in line two of the example above.

Demo

Here’s an interactive demo that should help clarify how this all works.

Nullptr

When a pointer is initialized with no value it holds garbage and can lead to unexpected buggy results. In the example below, uncommenting line 4 will product a different result.

For this reason it’s important to initialize an empty pointer with nullptr  and also check against nullptr.