Pointer and Memory Allocation

1

I know which pointer stores memory address. And a variable stores a value. But taking into account that I have a class class player {} and I create a variable player p; and a pointer instance player *np = null; What's the difference between these 2 declarations. What happens in the system, what are the advantages of using one or the other.

Considering the same class used earlier, I could say that creating an object of type player and also creating a pointer of the same type and storing the address of that object is the same as creating a new player() ? That is:

player x;
player *z = &x;

is equivalent to:

player *z = new player
    
asked by anonymous 09.04.2018 / 03:50

1 answer

1
  

I know which pointer stores memory address.

A pointer is a memory address.

  

And a variable stores a value.

Yes, even this value can be a pointer.

  

But taking into account that I have a class class player {} and I create a variable player p; and a pointer instance player *np = null; What's the difference between these 2 declarations. What happens in the system, what are the advantages of using one or the other.

The first one is in the stack and the second is in the heap . This has a number of implications, advantages and disadvantages .

  

Considering the same class used earlier, I could say that creating an object of type player and also creating a pointer of the same type and storing the address of that object is the same as creating a new player() ?

Not exactly, but I think I understand what you are saying, so we can say that they are almost equivalent, but each one's memory allocation is in a different place and has a different lifespan.

    
09.04.2018 / 04:09