Question 1: void fun(int *p){ static int q = 10; p = &q;} int main(){ int r = 20; int *p = &r; fun(p); printf("%d", *p); getchar(); return 0;} |
Output: 20
Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains unaffected.
Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains unaffected.
Question 2:
void fun(int **p){ static int q = 10; *p = &q;} int main(){ int r = 20; int *p = &r; fun(&p); printf("%d", *p); getchar(); return 0;} |
Output 10
Note that we are passing address of p to fun(). p in fun() is actually a pointer to p in main() and we are changing value at p in fun(). So p of main is changed to point q of fun(). To understand it better, let us rename p in fun() to p_ref or ptr_to_p
void fun(int **ptr_to_p){ static int q = 10; *ptr_to_p = &q; /*Now p of main is pointing to q*/} |
No comments:
Post a Comment