Mirror_Boy047
Mirror_Boy047

Reputation: 33

c++ pointer issue - update pointer through method

I am new to c++ programming. Playing around a bit with pointers. But i don't understand how the program given below printing 20 instead of 10.

According to me it should be 10! but it prints 20.

I want to get a clear concept in pointer but its getting harder a bit. It would be really helpful if anyone explain with details.

TIA

void fun(int *p) 
{ 
  int q = 10; 
  p = &q; 
}     

int main() 
{ 
  int r = 20; 
  int *p = &r; 
  fun(p); 
  printf("%d", *p); 
  return 0; 
}

Upvotes: 1

Views: 882

Answers (3)

songyuanyao
songyuanyao

Reputation: 172924

The parameter pointer p is passed by value, then any modification on p itself (instead of the object pointed by p) has nothing to do with the argument pointer being passed.

You can make it pass-by-reference, e.g.

void fun(int *&p) 
{  
    p = new int(10); 
}

then

fun(p); 
delete p;

Or make it pass-by-pointer.

void fun(int **p) 
{  
    *p = new int(10); 
}

then

fun(&p); 
delete p;

PS: In your code you're trying to assign the pointer to the address of local variable q, which is destroyed when get out of the function, left the pointer danlged. After thant any deference on it (e.g. *p) leads to UB.

Upvotes: 3

Alexey Medvedev
Alexey Medvedev

Reputation: 59

Going further (to better understand pointers) :)

void f(int *p) {
int q = 10;
*p = q;

} This works too. What happens here? The p is the argument that is the copy of the original pointer. But this argument contains address to original outer variable. "*p" names dereference the pointer to access to value that addressed by it. "*p = " means change the value by address that contains argument p.

Upvotes: 0

Daniel
Daniel

Reputation: 7724

@songyuanyao already answered, but just to help you understand, run this code and try to realize the difference:

void fun(int &p) 
{ 
  int q = 10; 
  p = q; 
}     

int main() 
{ 
  int r = 20; 
  int *p = &r; 
  fun(*p); 
  printf("%d", *p); 
  return 0; 
}

Here the output is 10, as you thought it would be. Can you figure out why?

Upvotes: 0

Related Questions