Saturday, April 19, 2025

C++ Dereferencing a Pointer

We learned that a pointer is variable that holds memory address of some real variable that holds value.

Now, dereferencing means that we will get VALUE of ORIGINAL variable using memory address.

First, we will create original variable PI, data type is float. Value is 3.14.

float PI = 3.14;

Then, we are creating a pointer that will provide us memory address of an original variable.

float *ptrPI = Π

Ok, now we have both value and pointer set up. 

That means we can dereference a pointer to get original value:

And we can get a pointer itself, which is just memory address of original value.

Please note, we ARE NOT using original variable name to get real original data (3.14). ALL the time we are using pointers:

#include <iostream>

using namespace std;

int main() {

    float PI = 3.14;
    float *ptrPI = &PI;

    cout << "Actual Value In That Address: " << *ptrPI << endl;
    cout << "Actual Address: " << ptrPI << endl;

    return 0;

}

Result:

Actual Value In That Address: 3.14
Actual Address: 0x6dfee8

Process returned 0 (0x0)   execution time : 0.077 s
Press any key to continue.

Perhaps it's weird that we are using symbol "*" two times here.

But first time we use it to CREATE a pointer and second time to DEREFERENCE pointer so we can get ORIGINAL value from a memory address.

Pointers and Constants

We can play around with constants too. They are created above main() section.

If a constant is of data type string (for example), a pointer must be also of same data type.

Once we have a pointer, we can print it to get memory address, or we can dereference it (using "*" symbol)  to get real value in ORIGINAL constant.

You will get used to pointers in C++, don't worry.

#include <iostream>

using namespace std;

const string STR = "Slavoj Zizek vs J.Peterson";

int main() {

    const string *ptrSTR = &STR;

    cout << "Actual Address: " << ptrSTR << endl;
    cout << "Actual Value: " << *ptrSTR << endl;

    return 0;

}

Result:

Actual Address: 0x4c600c
Actual Value: Slavoj Zizek vs J.Peterson

Process returned 0 (0x0)   execution time : 0.056 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...