问题描述
大家好,
我正在写一个函数,它返回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
推荐答案
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
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实际上是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的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!