![](/img/trans.png)
[英]In C, I understand why not to return the address of a local variable in a pointer returning function, how can I fix it though?
[英]How can a function returning the address of the variable return zero?
#include<stdio.h>
int *addressof();
int main()
{
int *p=addressof();
printf("%u",p);
return 0;
}
int *addressof()
{
int x=9;
return &x;
}
Output:
0
变量的地址可以为零吗? 可能吗?
您编写的代码具有未定义的行为,因为它返回了当 function 返回时将被释放的局部变量的地址。 在这种情况下,编译器可以选择对其进行优化并返回 0。
如果您将变量更改为 static 而您返回的地址将是有效的
int *addressof()
{
static int x=9;
return &x;
}
检查编译器的警告,第二个问题是,指针的大小不一定与unsigned long
相同,将printf
中的"%u"
替换为"%p"
。
注意:这是对这个答案的补充,它涵盖了你得到零的一些原因。
根据您的目标系统及其编译器,变量的地址当然可以为零。 例如在 MCS51 微控制器上就是这种情况,其中(外部)RAM 从 0 开始并用于变量。 不幸的是,在该系统中NULL
也被定义为零指针,这使得常见用法变得困难。
printf("%p",&p);
您将获得 output。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.