![](/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?
[英]I cannot return pointer to local variable, but I can return pointer to data of local struct in c?
我知道返回指向局部变量的指针不是一个好主意,因为用于该变量的堆栈将被重用。 这样:
#include <stdio.h>
int *func(){
int x = 10;
return &x;
}
int main(){
printf("%p\n",(void*)func());
}
按预期打印(nil)
。
但是,为什么我可以返回指向本地结构数据的指针? :
#include <stdio.h>
struct foo{
char c;
int *p;
};
int *func(){
struct foo f;
f.c = 'c';
int local = 10;
f.p = &local;
return f.p;
}
int main(){
int *b = func();
printf("%d\n",*b);
}
struct foo f
在 function func
中是本地的,因此每个本地变量都应该有相同的规则——即自动存储在堆栈中。 我还没有查看它的汇编程序 output 来确认这一点,但是如果这个假设不成立,那么为什么要对结构类型进行特殊处理呢? 在我查看 asm 之前,是否将 struct foo 存储在堆栈中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.