why this function does not change pointers value?

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();
}

2 answers

  • answered 2018-02-13 01:28 Lightness Races in Orbit

    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.

  • answered 2018-02-13 01:28 Saliou673

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

    p = &q