Search code examples
c++pointers

Pointers, ampersands and pointers again?


I just cannot get my head around pointers - when and how exactly I am supposed to use pointers. No matter how many videos and literature I read on it, I just do not understand when and how I am supposed to use it. I am that dense apparently...

Let us look at this example here:

int main()
{
    int* ptr = new int(10);

    std::cout << ptr << std::endl; 
    std::cout << *ptr << std::endl; 
    std::cout << &ptr << std::endl;
}

This would return us a value like this:

000001A68ABB5250 
10 
000000455ADCF828

What do these outputs mean? The first and the third look like they are address number in memory but they are different and I do not understand what are they supposed to do? The second one is the value I assigned but why do I have to get it with a pointer symbol?

Let us have a look at this:

int main()
{
    int ptr = 10;

    std::cout << ptr << std::endl; 
    //std::cout << *ptr << std::endl; //gives "Error(active)    E0075   operand of '*' must be a pointer but has type 'int'"
    std::cout << &ptr << std::endl;
}

Which respectively returns:

10
000000D9242FF5F4

What makes the code above different to this example code? Why don't I have to use pointer to get the value? Ampersand show us the memory address right?

Essentially can someone explain to me in the silliest, easiest to understand way what is the point of pointers and why do we need them in C++.


Solution

  • If we "draw" the first example it will be something like this:

    +------+     +-----+     +--------------+
    | &ptr | --> | ptr | --> | *ptr int(10) |
    +------+     +-----+     +--------------+
    

    So ptr is pointing to an int value (initialized 10 10). And &ptr is pointing to the variable ptr.


    In the second example the variable name ptr is misleading since it's not a pointer. It's a plain int variable.

    Drawn it will be like

    +------+     +-------------+
    | &ptr | --> | ptr int(10) |
    +------+     +-------------+