What does putting '*' in front of a variable affect?

Question:

I know that '*' is used to define a pointer at the time of creating a variable, for example:

objeto* variable;

But, in this case of a university exercise:

function_init(tPopularity* object) {
    tPopularity newPopu;

    /*Relleno de de datos, no importante para la pregunta*/

     object=&newPopu;
}

My initial idea was to leave is the one above, that is:

 object=&newPopu;

The problem is that when exiting the function the data of the object was lost, so what I have done, without really knowing why is:

 *object=newPopu;

And works! My data is not lost and the tests pass correctly … now my question is … Why are my results now as expected? Why was the data corrupted and why not now? What does that asterisk in front of an assignment mean in my code?

Answer:

Why was the data corrupted and why not now?

If we use variables it looks better:

void func(int var)
{
  var = 10;
}

int main()
{
  int a = 0;
  func(a);
  std::cout << a;
}

It does not matter how many times you run the previous code that will always print 0 and the reason is very simple: var is a copy of a , then the changes we make on var will not have their echo in var . It's like cloning a sheep … shearing the clone is not going to automatically shear the original sheep.

Now we are going to see the same example but with pointers:

void func(int * var)
{
  int n = 10;
  var = &n;
}

int main()
{
  int a = 0;
  int* ptr = &a;
  func(ptr);
  std::cout << a;
}

The program prints 0 … But we are using pointers! … ya, but like in the previous case, var is a copy of ptr . The only thing that both pointers share is that they point to the same memory address, but they are still independent variables.

And this is where the trick kicks in. What var=10 is modify the address pointed to by var . After this change, ptr will point to a memory address and a a different one.

Now, instead, imagine that we change the example a bit:

void func(int * var)
{
  int n = 10;
  *var = n;
}

Now the program will magically print a 10 !!!

What happened now?

What happens now is that, thanks to the use of the asterisk, we are modifying the memory shared by both pointers, var and ptr .

That is why this change propagates outside of the function.

That said, I take the opportunity to clarify a small detail: In your first case, I don't know that the data was corrupted … it's that you weren't modifying the original memory , which was unchanged as it was when the function was called.

Scroll to Top