函数返回指针! ! ! [英] Functions returning pointers! ! !

查看:66
本文介绍了函数返回指针! ! !的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我的代码如下:

main(){

int * p;

int * fun();

p = fun();

printf(%d,p);

printf(%d,& p) ;

}



int * fun(){

int i = 20;

返回(& i);

}



我尝试了什么:



当控件从fun()返回时;我死了?然后,代码怎么能给我正确答案?

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?

推荐答案

你的fun()从其内部堆栈返回一个本地指针。这个堆栈被解除了,所以它是无效的。



我会这样做:

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:
int*fun(){
int *i= new int;
*i = 20;
return i;
}





重要提示:返回的int *必须得到释放





Important: the returned int* must get freed like that

int *p = fun();
printf("%d",*p);//deref pointer
delete p;//house keeping free the memory after use


这篇关于函数返回指针! ! !的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆