Code:
//Function returning a pointer to an int. (Memory address).
int *s(int c);
void main()
{
int y = 10;
//pointer to an int (memory address), which has a value of ten.
int *p = s(y);
//print the data the pointer points to, in this case a value of 10.
//If you used "p" rather than "*p", you'd get a memory address
printf("%d\n",*p); //Why it prints 10?
//irrelevant?
int temp = 11;
int *lol = 12;
//Memory address hasn't changed, still points to an int with a value of 10.
printf("%d\n",*p);//Why it prints 10?
}
//Function returning a pointer to an int.
int *s(int c)
{
int a = c;
//You're finding the memory address of a. What did you expect it to print?
printf("%d\n",&a);//Here it prints the memory address of a
//It doesn't. It returns a pointer to an int of value 10.
//This is a bad idea, btw. See: http://stackoverflow.com/questions/8184315/why-does-gcc-throw-a-warning-when-returning-a-pointer-to-a-local-variable-and-no
return &a; //Here it returns 10. Why?
}
I've commented your code. I think you probably need to read up on pointers a little more.
No doubt the REAL programmers here will correct me further, but oh well.
Bookmarks