-3

Why does the last printf output -2?
Isn't it supposed to output 2?
Is there an explanation for this?

#include <stdio.h> 

void foo(int **);

int main()
{
     int x=20;
     int *p;

     p=&x;
     printf("%d\n",&x); 
     printf("%d\n",p); 
     printf("%d\n",&p); 
     foo(&p);
     printf("%d\n",p); 
     printf("main%d\n",*p);
}

void foo(int **p)
{
     int j=2;
     printf("%d\n",p); 
     printf("%d\n",*p);
     *p=&j;
     printf("%d\n",*p);
     printf("%d\n",**p);
}
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
vishal
  • 7

1 Answers1

2

Your int j=2; is local to function foo.

You are accessing it after the function returns leading to undefined behaviour and thus may print 2 or some other value.

If you change int j = 2 to static int j = 2 in your example then you can always expect output of 2.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • even if i use any other value for j the outout is -2 only. Any reason for that. – vishal Jul 23 '14 at 08:01
  • Exactly my point. You can think of this as, in function foo, you gave life to a variable `j` and value of 2 and kept the address of var `j`. After the function ends, `j` is dead (for detail read about [life and scope of variable](http://stackoverflow.com/questions/7632120/scope-vs-life-of-variable-in-c)). Because there is nothing like `j` any more you are pointing to something else which may print a value of `2` or something else. It may be different on different OS, compilers etc so even if it works as intended on some target, this is **not** the right way to do things. – Mohit Jain Jul 23 '14 at 08:44