Saturday, April 19, 2025

C++ Pointers Explained

Pointers are easy.

A pointer is a variable, but it stores the memory location (address) of real value we provide in some other variable.

They are like real GPS coordinates of some house. Yes, we need to know real street number of some house, but pointers are more like GPS coordinates.

You can think about them as excel table where combination of a row and column will tell us real value in that cell.

Except we are talking about real memory chips here, hardware location of values.

Of course, hardware locations are fixed, but values in them (just as in Excel cells) can change.

So, it's easy to get any value just knowing exact memory location (we have just printed location here, pointer creation will be explained too):

#include <iostream>

using namespace std;

int main() {

    int number = 1000;

    cout << "Actual value: " << number << endl;

    cout << "Address of container for number: " << &number << endl;

    return 0;

}

Result:

Actual value: 1000
Address of container for number: 0x6dfeec

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

So far so good.

Now we will create a pointer that will point to memory location we printed above:

On left side of pointer name we must have data type same as value data type and special "*" symbol for pointers.

Once we create a pointer, there is no need to use "*" symbol while using a pointer to print memory location:

#include <iostream>

using namespace std;

int main() {

    int number = 1000;

    cout << "Actual value: " << number << endl;
    cout << "Address of container for number: " << &number << endl;

    int *pointer_to_number = &number;

    cout << pointer_to_number << endl;

    return 0;

}

Result:

Actual value: 1000
Address of container for number: 0x6dfee8
0x6dfee8

Process returned 0 (0x0)   execution time : 0.182 s
Press any key to continue.
Don't worry if you don't understand pointers at the moment, give yourself a little bit of time.

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 .  ...