-2

The output prints the same value - 8; I am not able to get why *p = 15 does not modify the the pointers value?

void foo(int *p) {
    int q = 19;
    p = &q;
    *p = 15;
}
int main() {
    int x = 8;
    int *y = &x;

    foo(y);
    cout << x << " " << *y << endl;

    cin.get();
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
DKay
  • 5
  • 1

2 Answers2

1

You have changed the adress of q when execute the follow instruction in the function

p = &q
Saliou673
  • 209
  • 2
  • 10
0

It does modify the value pointed-to, but when it does so the pointer is pointing to the variable q in foo, not the variable x in main (which remains unchanged).

The other part of the puzzle is that, at that time, the pointer in question was a copy of the original pointer. There is no relationship between the p in foo, and the y in main, other than p begins life initialised with y's value.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I suggest running through the steps of your program on paper and track the value of everything as you go. You will soon find out where you went wrong in your mind (and, if not, then you have something more concrete to ask us). This is called "debugging". – Lightness Races in Orbit Feb 13 '18 at 01:34