I am trying to return the value stored in a local variable to the main() function.
#include<stdio.h>
int *func();
int main()
{
int *ptr;
ptr = func();
printf("%d", *ptr);
printf("%d", *ptr);
return 0;
}
int *func()
{
int x = 5, *p;
p = &x;
return p;
}
The first printf() statement gives output = 5, but the second printf() statement gives a garbage value as output.
I know that the local variable 'x' will not exist after the function "func()" terminates. Then why is it printing 5 for the first printf() statement?? Please tell me what is happening inside the code.