Skip to main content
C++

Pointers in C++: The newbies guide

By January 21, 2020May 1st, 2020No Comments

Pre-requisite

You know pointers are important so you’re reading this

How is data stored?

When you declare variables, they are assigned a location in the computer’s memory. This location/address is actually where the value of the variable is stored. Let’s see a small example. You might not understand the code right, now that’s ok. Just pay attention to the output of cout and how it is unique
Here you see that the 3 different cout outputs are: 0x7ffc798e318c
0x7ffc798e3188
0x7ffc798e3184 The 0x in the beginning means that it is in hexidecimal format. You may notice that all the 3 address are different. This is because the variables and variable values are stored at different memory locations.

The superpowers of Pointers

Pointers give you access to the exact memory location of a variable, so you can: 1. Manipulate values by accessing the memory location of a variable. 2. You can also assign/de-assign locations

Definition

A pointer is a variable whose value is the address of another variable. In another words ” A C++ pointer is just a variable that stores the memory address of an object in your program.” Additionally, a pointer can also store the address of another pointer. And pointers can also be incremented/++ and decremented — to point to the next or previous memory location Another definition: A POINTER stores the memory address as its value. Bjarne says: A pointer is a machine address with a type associated with it at compile time. So think about it when you code something like i++, how is the value of i being incremented by 1? It’s because there is a reference to what the value of i is currently.

Example

  1. In this case variable int num1 will store the value of 10
However each variable besides storing the value also stores the address of where the variable is located in memory. You can access this with the ampersand (&) symbol. So in this case you can get the memory address of a variable

What? I’m confused! Is a variable a pointer?

A variable is a stored value in a memory address. For example: int x = 10; Whereas a pointer is a variable that is a reference to the address of another variable/value. For example: int* num1Pointer = &num1;

How to pointer?

  1. Declare a pointer
We use the * symbol which is called a deference operator
2. Get the value at the memory location stored that the pointer points to with the * deference symbol
Let’s cout what’s going on anyways
2. Change the value of a pointer When you change the value of a pointer you also change the value of the original variable

Leave a Reply