Question

Given the following code:

void Allocate(int *p)
{
    p = new int;
    *p++ = 2;
}

int main()
{
    int i = 10;
    Allocate(&i);
    std::cout << i << std::endl;
}

I'm a bit confised about the meaning of:

*p++ = 2;

The output is 10 and my reasoning as to why this is the case is that *p++ is a temporary therefore any assignment to it is lost at the end of the scope of Allocate(int *p).

Is this the case? Thanks in adv!

Was it helpful?

Solution 2

when you pass the the address of i into Allocate, another (temp) pointer is created that points to i's address (i.e. passing by pointer). then that temp pointer is pointed to a new location (via new int). thus the value of i is left alone.

here's a crappy illustration i drew

OTHER TIPS

  • On input to Allocate, p points to the variable i in the main function.
  • The address of this variable then lost and replaced by the new int.
  • The value of this int (which is uninitialized and so could start as anything) is set to 2.
  • The p pointer is incremented.
  • The Allocate function returns at this point, leaking the int that was allocated.
  • The value of i in the main function is unchanged, because Allocate did not modify it.
p = new int;

You're assigning p new memory to point to instead of what it was pointing to before. You then change this newly allocated memory and it's lost forever when the function ends, causing a memory leak. If you remove the allocation line, it should cause an output of 2. The ++ does nothing in this case. It just increments the pointer and returns the old value to dereference.

As soon as you enter Allocate, you assign p to point to a new block of memory, so it no longer points to i. Then you modify that new block of memory (which is then leaked when the method returns.) i is unaffected because you've moved that pointer before you set the pointed-to memory cell.

void Allocate(int **p)
{
    *p = new int;
    **p = 2;
}


int main()
{
    int j = 10;
    int *i = &j;
    std::cout << i << std::endl;
    Allocate(&i);
    std::cout << i << std::endl;
}

Output is : 10 2

You need a pointer to pointer to change the address of the location being pointed to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top