Click here to Skip to main content
15,888,293 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi expert,my code is given below:
main(){
int *p;
int *fun();
p=fun();
printf("%d",p);
printf("%d",&p);
}

int*fun(){
int i=20;
return(&i);
}

What I have tried:

When the control comes back from fun(); I dies? Then, how could still the code give me the correct answer?
Posted
Updated 12-Mar-16 7:11am
Comments
Richard MacCutchan 13-Mar-16 6:47am    
Your time would be better spent studying of a good C reference manual. You will not learn a programming language by posting questions here.

1 solution

your fun() is returning a local pointer from its internal stack. This stack got deallocted, so it is invalid.

I would do it this way:
C++
int*fun(){
int *i= new int;
*i = 20;
return i;
}


Important: the returned int* must get freed like that

C++
int *p = fun();
printf("%d",*p);//deref pointer
delete p;//house keeping free the memory after use
 
Share this answer
 
Comments
[no name] 12-Mar-16 13:44pm    
A 5 because you Show how to solve it in real live. A 1 because you did not answer the question "Then, how could still the code give me the correct answer?"

Because the first Counts a lot 5 & 1 remains 5 ;)
Aescleal 14-Mar-16 13:17pm    
Your solution doesn't look like C...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900