函数返回int的指针? [英] function return pointer of int?

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

问题描述

大家好,


我正在写一个函数,它返回int的指针。但它似乎是错误的
。有什么建议吗?


int * get_p_t(int t){

return& t;

}


int main()

{

printf(" v1 \ n");

int t = 5;

int * p_t [2];


p_t [0] =& t; //对

p_t [1] = get_p_t(t); //错


返回0;

}


祝你好运,

Davy

Hi all,

I am writing a function, which return the pointer of the int. But it
seems to be wrong. Any suggestion?

int * get_p_t(int t) {
return &t;
}

int main()
{
printf("v1\n");
int t = 5;
int * p_t[2];

p_t[0] = &t; // right
p_t[1] = get_p_t(t); //wrong

return 0;
}

Best regards,
Davy

推荐答案

Davy写道:
Davy wrote:

大家好,


我正在写一个函数,它返回int的指针。但它似乎是错误的
。有什么建议吗?


int * get_p_t(int t){

return& t;

}
Hi all,

I am writing a function, which return the pointer of the int. But it
seems to be wrong. Any suggestion?

int * get_p_t(int t) {
return &t;
}



t实际上是get_p_t中的局部变量。因此,您返回的地址

将在函数返回后无效。


-

Ian Collins

t is effectively a local variable in get_p_t. So the address you return
will be invalid after the function returns.

--
Ian Collins


11月5日,2:49 * pm,Ian Collins< ian-n ... @ hotmail.comwrote:
On Nov 5, 2:49*pm, Ian Collins <ian-n...@hotmail.comwrote:

Davy写道:
Davy wrote:

大家好,
Hi all,


我正在编写一个函数,返回int的指针。但它似乎是错误的
。有什么建议吗?
I am writing a function, which return the pointer of the int. But it
seems to be wrong. Any suggestion?


int * get_p_t(int t){

* * return& t;

}
int * get_p_t(int t) {
* * return &t;
}



t实际上是get_p_t中的局部变量。 *因此,在函数返回后,您返回的地址

将无效。


t is effectively a local variable in get_p_t. *So the address you return
will be invalid after the function returns.



你好,Ian,谢谢,

但是如何在main()范围内获取t的地址,如果我想

使用功能?

Hi Ian, thank you,

But how can I get the address of t in the main() scope, if I want to
use function?


>

-

Ian Collins
>
--
Ian Collins


Davy写道:
Davy wrote:

11月5日下午2:49, Ian Collins< ian-n ... @ hotmail.comwrote:
On Nov 5, 2:49 pm, Ian Collins <ian-n...@hotmail.comwrote:

> Davy写道:
>Davy wrote:

>>大家好,
我正在写一个函数,它返回int的指针。但它似乎是错的。有什么建议吗?
int * get_p_t(int t){
return& t;
}
>>Hi all,
I am writing a function, which return the pointer of the int. But it
seems to be wrong. Any suggestion?
int * get_p_t(int t) {
return &t;
}


t实际上是get_p_t中的局部变量。因此,在函数返回后,您返回的地址将无效。

t is effectively a local variable in get_p_t. So the address you return
will be invalid after the function returns.



您好,Ian,谢谢,

但是如何在main()范围内获取t的地址,如果我想

使用功能?


Hi Ian, thank you,

But how can I get the address of t in the main() scope, if I want to
use function?



你不能。你得到了t的地址。


-

Ian Collins

You can''t. You get the address of where t was.

--
Ian Collins


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

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