How to Dereference a Pointer in C++

Hey Guys, Today We will be discussing how to dereference a pointer in C++.
This is really helpful since it helps us understand the use and purpose of a pointer.
So let us get right to it.

How to Dereference a pointer in C++

So what is a pointer in C++? (Pointers and references in C++)
Pointer is nothing but something that points to a value.
It stores the address of a value and points to it when called.

Pointers are helpful in programming as they help in making the program faster and along with that they can access variables that are defined outside a function

There are 2 important parts when it comes to using a pointer:
1) Referencing
2) Dereferencing

To understand Dereferencing, we would first have to understand what referencing means.

Referencing a Pointer

Referencing means taking an Address of an existing variable and storing it in a pointer.
Here we use the Ampersand (&) symbol.

Take a look at the following code:

#include <iostream>
using namespace std;
int main()
{
    int a;
    int* b;
    a = 123;
    b = &a;
}

Here b references a.

So let us understand what is happening here.
So 123 gets stored in a.
b that is of a pointer type stores the address of a.

To illustrate this we will print the value of b using “cout<<b;”

0x7ffdb9c7be44

This is not 123. This is the address where 123 is stored.
Now when you try this, this address may not be the same since we have different memory usage, etc.

But now we cant use this address anywhere. It is pointless. That brings us to dereferencing a pointer.

Dereferencing a Pointer in C++

Dereferencing a pointer means taking the address stored in a pointer and finding the value the address points to.
We use the Asterix (*) symbol here.

Take a look at the code below:

#include <iostream>
using namespace std;
int main()
{
    int a,c;
    int* b;
    a = 123;
    b = &a;
    c = *b;
}

So what is happening here?

Till the ” b = &a ” line, everything is exactly the same as the code in referencing a pointer
But the “c = *b ” is an add on.

So Here the value c gets the value b is pointing to.

It gets the address from *b, finds the address, gets the value stored in there (i.e. 123).

So if we print c using ” cout<<c; “, we should get

123

Therefore we have made use of a pointer by dereferencing it.

To be Noted while using pointers:

  1. Dereferencing an uninitialized pointer can cause a crash
  2. Dereferencing a different data type’s pointer can cause a crash
  3. Trying to Dereference a pointer to a variable that is out of scope can also cause a crash

 

And that is all. Do feel free to play around with the pointers and with different values. I hope you understood the logic and were able to execute it by yourself. If you have any doubts regarding this, feel free to ask it in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *