For the complete documentation index, see llms.txt. This page is also available as Markdown.

🦋Pointers

Address of Variables

So far, we've been working with variables like:

main.cpp
int x = 10;

But sometimes, we don't want the value itself, rather we will want to know where is this value stored in memory?

The variable x could have some address like 0x100...

We don't know so lets find out using the ampersand & operator.

Type of Pointers

We know the type of x is an integer , but what's the type of &x ?

Instead of second guessing ourselves, let's rely on the C++ compiler to tell us. C++ offers a typeid function that seems useful:

The output may look cryptic but:

  • i (as you might have guessed) represents int

  • Pi (which you also might have guessed) represents pointer to int (int*)

Indeed, we can write it like so:

Code
Visual Aid

De-referencing

Given a pointer of type (int *), is there a way I can get the actual value (and not the address) it points to?

In other words,

Yes we can! Since the pointer p stores an address, we can dereference the pointer using * to get the value! Think of dereferencing as follow the address to get the value stored there.

Code
Visual Aid

Realise while both values of x and y are the same, they are not pointing to the same 10. They each contain their own version of 10 (and possess their own memory addresses).

How do you make x and y to point to the same 10 then?

Simple: we don't make two variables. We declare 1 variable and multiple pointers to the same variable.

Pointer-Ception

And yes because pointers also have addresses, we can have pointers that point to a pointer that points to a value.

Code
Output

Last updated