Tuesday, January 17, 2012

C Parameter Passing


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.
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*/
}
Also, note that the program won’t cause any problem because q is a static variable. Static variables exist in memory even after functions return. For an auto variable, we might have seen some weird output because auto variable may not exist in memory after functions return.

No comments:

Post a Comment