Hi Raghu,
You are trying to return a local variable address here. What happens in the
cpu when a function is called ? The life time of the local variable is only
within the function, why ?
Hope you know about the PC(program counter) and SP(stack pointer) if not a
PC is a cpu register where the address of the next instruction to be
executed is stored. SP is a cpu register holds the address of top of the
Stack.
When a function is called the PC value has to be altered on the fly and it
has to execute the instructions of the subroutine(or funtion) and once it is
done it has to 'return' back to the calling routine and execute instruction
from where is left.
The stack comes to picture here, when function is called a stack frame is
created and the return address, the function arguments are variables are
'Pushed' on to the stack and now it changes the PC register to the
subroutine's instruction address and start executing the subroutine. Once
it is done it will 'return' by Poping out the return address from the stack
and when doing this the SP is decremented. The contents in stack will be
still there until when some other function is called and alters the value.
In your case that is the reason you see 10, which is expected with the above
theory.
Geeks,
I am open for discussion on this topic...
Thanks,
-Kumar.
"raghu" <ra*********@gmail.comwrote in message
news:11**********************@a3g2000cwd.googlegro ups.com...
#include<stdio.h>
int *f1()
{
int a=20;
return &a;
}
f2()
{
int b=10;
return b;
}
int main(void)
{
int a;
int *p;
p=f1();
f2();
a=*p;
printf("%d",a);
}
The output should be 20..am I right???
When I compiled the program in Turbo C/C++ ....the output is 10 i.e b
value....How is that possible?
Please help.