Riley Miller

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;
2
3int * x;
4
5x = &a;
6
7std::cout << x << std::endl;
8

Outputs:

1$ ./address-of
20x2ABF1231
3

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;
2
3int * x;
4
5x = &a;
6
7std::cout << *x << std::endl;
8

Outputs:

1$ ./value-of
21
3

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;
2
3int * x;
4
5x = &a;
6
7std::cout << *x << std::endl;
8
9*x = 4;
10
11std::cout << a << std::endl;
12std::cout << *x << std::endl;
13

Outputs:

1$ ./value-of
21
34
44
5

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 1: Pointer Initialization Graphic Step 2: Copy Pointer Step 2: Copy Pointer Graphic

Here is the underlying code for the visualization above.

1int * x;
2int * y;
3
4int val_1 = 32;
5int val_2 = 67;
6
7x = &val_1;
8y = &val_2;
9
10std::cout << *x << std::endl;
11std::cout << *y << std::endl;
12
13x = y;
14
15std::cout << *x << std::endl;
16std::cout << *y << std::endl;
17

Outputs:

1$ ./copy-pointer
232
367
467
567
6

Written by Riley Miller, follow me on Twitter 🐦

//