#include<stdio.h>
int main()
{
int var=100;
int *ptr=&var;
fun(&ptr);
printf("%p",ptr);
printf("%d\n",*ptr);
}
int fun(int **var)
{
int j=10;
*var=&j;
printf("%p\n",*var);
printf("%d\n",**var);
}
Output:
0x7fff2c96dba4 10 0x7fff2c96dba4 10
How is value getting retained even after function completing execution? I executed it several times in gcc and in online compiler it gives the same result. please help me in understanding this...Thanks In advance.
How is value getting retained even after function completing execution?
Undefined behavior (UB). It might appear to "work", but that is not specified to be so by C.
fun(&ptr);
runs fine, yet printf("%p",ptr);
is UB as the value ptr
is no longer valid. Many systems will tolerate this UB.
De-referencing ptr
, with printf("%d\n",*ptr);
is even worse UB. More likely to behave badly. Best not to attempt either of these.