C++ Pointers Basics
July 30, 2020
Photo from Unsplash byKen Reid
Code referenced in article.
C++ pointers are an extremely powerful primitive in the programming language which allows developers to directly manipulate memory during program execution.
Pointers usually get a bad rap for being confusing or “dangerous” but once you dig in and begin to understand them, they’re pretty intuitive.
The C++ docs broke pointers down in a way that I really liked focusing on two commonly used operators when working with pointers: *
and &
.
Pointer Initialization
Pointers are a data type that are used to store the memory addresses of other data types.
To initialize a pointer declare the data type, use the *
operator, and then give the pointer
a name like the example below.
1int * x;2int * y;3
Address-of operator (&)
The docs refer to &
as the “address-of” operator.
When the &
is used to prefix data in C++, it returns the memory address of the data on the stack or heap.
1int a = 1;23int * x;45x = &a;67std::cout << x << std::endl;8
Outputs:
1$ ./address-of20x2ABF12313
Since pointers store a memory address, this is typically how a pointer is initialized or set.
Dereference Operator (*)
After a pointer is initialized, the *
operator is used as the “value-of” operator. Where dereferencing a pointer returns the value
that is held in the memory address stored by the pointer.
1int a = 1;23int * x;45x = &a;67std::cout << *x << std::endl;8
Outputs:
1$ ./value-of213
Change Value of Pointed-to Data
One of the neat features of pointers is how they can be used to modify the data of the memory address
that is stored in the pointer. This is accomplished using the dereference operator (*
) on the lhs of the expression.
1int a = 1;23int * x;45x = &a;67std::cout << *x << std::endl;89*x = 4;1011std::cout << a << std::endl;12std::cout << *x << std::endl;13
Outputs:
1$ ./value-of2134445
Copy Pointers
Although Pointers have many interesting applications, they can also be copied and initialized just like any other data type. When a pointer is set equal to another pointer, it will copy the memory address that was held in the rhs of the expression into the pointer on the lhs of the expression. This can be expressed visually with two simple steps.
Step 1: Pointer Initialization Step 2: Copy Pointer
Here is the underlying code for the visualization above.
1int * x;2int * y;34int val_1 = 32;5int val_2 = 67;67x = &val_1;8y = &val_2;910std::cout << *x << std::endl;11std::cout << *y << std::endl;1213x = y;1415std::cout << *x << std::endl;16std::cout << *y << std::endl;17
Outputs:
1$ ./copy-pointer2323674675676
Written by Riley Miller, follow me on Twitter 🐦