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:
int myInt = 8; // Allocates an int on the stack and initializes with the value 8 int *myIntPtr = &myInt; // Allocates an int pointer to the stack, initializes with address from myInt
One can visualize the memory like so:
*myIntPtr
0x400710 | 0x400711 | 0x400712 | 0x400713 |
---|---|---|---|
0x672030 |
myInt
0x672030 | 0x672031 | 0x672032 | 0x672033 |
---|---|---|---|
8 |
Common Operators
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
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.
int *i = nullptr; if(i != nullptr) { // do something }