Search code examples
cpointersfunction-calls

Shifting pointer to some address by calling another function


Why in this code the pointer shifts to another location:

#include <stdio.h>

void f(int *p)
{
        int j=2;
        p=&j;
        printf("%d\n%p\n%d\n",*p,&j,p);
}

int main(void)
{
        int *q;
        int m=98;
        q=&m;
        f(q);
        printf("%p ",q);
        return 0;
}

Output:

2
0x7ffff5bf1bcc
0x7ffff5bf1bcc
0x7ffff5bf1bc8

I understand that when the function f() is done with printing value of j and address of j the memory occupied by j goes back to the stack but IMO p should continue pointing that location even after the function is over & it should be printing the same address in main as well. What is wrong with this?


Solution

  • Learn the difference between Pointers and Pointers to pointers - the pointer passed p is no doubt good to change the value of the variable it is pointing to (m), but to change the memory location it is pointing to - you need a pointer to pointer.