![](/img/trans.png)
[英]I cannot return pointer to local variable, but I can return pointer to data of local struct in c?
[英]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?
我有以下代码:
int* foo(){
int x = 15;
return &x; }
我理解为什么不这样做,因为在函数完成后局部变量地址从堆栈中被擦除并且它变成了一个悬空指针。 问题是,如何在不使 xa 静态变量的情况下使其成为悬空变量
从函数内部的堆分配内存
int *f() {
int *foo = malloc(sizeof(int));
if(!foo) {
// Do appropriate error handling here
}
return foo;
}
不要忘记在某个时候free
它。
或者你传入一个指向位于函数外部的变量的指针:
void f(int *foo) {
*foo = 42;
}
void g() {
int goo;
f(&goo);
}
有福的方法是:
返回一个值而不是地址
int foo(){ int x = 15; return x; }
让来电者提供地址
int *foo(int *x) { *x = 15; return x; }
或者
void foo(int *x) { *x = 15; }
返回动态(已分配)内存:
int *foo() { int *x = malloc(sizeof(*x)); // should test valid allocation but omitted for brievety *x = 15; return x; }
请注意,调用者将获得所有权或分配的内存,并负责稍后释放它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.