#include <stdio.h>
#include <stdlib.h>
int* test(int); // the prototype
int main()
{
int var = -20;
int *ptr = NULL;
ptr = test(var);
printf("This is what we got back in main(): %d \n", *ptr);
return 0;
}
int* test(int k)
{
int y = abs(k);
int *ptr1 = &y;
printf("The value of y in test() directly is %d \n", y);
printf("The value of y in test() indirectly is %d \n", *ptr1);
return ptr1;
}
The output is:
The value of y in test() directly is 20
The value of y in test() indirectly is 20
This is what we got back in main(): 20
Short Summary: The above mentioned code has a user defined function which returns a pointer that holds the address of a variable(i.e.,y). This variable is assigned an absolute value of the integer passed to the function (i.e.,x)
My book " Computer Programming for Beginners" by A.J.Gonzalez states the following: The variable y will cease to exist after the function exits, so the address returned to the calling function will turn out too be meaningless. However the value held in its address will persist and can be retrieved through the pointer.
My question is : How did we come to this conclusion that a value held in the address will persist and can be retrieved through the pointer from the following printf statements:
1st statement: giving value directly using y.
2nd statement: using a pointer to give the value.
3rd statement: getting the value from main.
All that is all right but then from there how does one make the conclusion that the direct use variable loses its value but the indirectly used variable (i.e., the pointer ) retains its value ? I tried looking at past questions but could not find anything relevant.
Will be grateful for your help. Thank You.