Home > OS >  Pointers, ampersands and pointers again?
Pointers, ampersands and pointers again?

Time:02-26

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?

CodePudding user response:

When I first started programming, pointers were one of the things where I just accepted they work and eventually built up enough experience to learn/understand them.

In one of my classes, a professor said it is best to use pointers when you want to modify an object but not make a copy of it. Passing by value to functions creates a copy of the object being passed inside of it.

CodePudding user response:

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

 ------       -----       --------- 
| &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) |
 ------       ------------- 
  • Related