[英]Returning pointer from function
Why this code doesn't work? 为什么此代码不起作用? I have already found a workaround by passing a pointer to the function but I wonder if there is an easier solution?
我已经通过传递指向函数的指针找到了解决方法,但是我想知道是否有更简单的解决方案?
#include <stdio.h>
int* func() {
int d[3];
for (int f = 0; f < 3; f++)
d[f] = 42;
return d;
}
int main() {
int* dptr;
dptr = func();
printf("Hi\n");
for (int f = 0; f < 3; f++)
printf("%d\n",dptr[f]);
return 0;
}
With return d;
return d;
, you are returning a pointer to a local variable, ie array d
's live time will end once function func
has finished. ,您将返回一个指向局部变量的指针,即一旦函数
func
完成,数组d
的生存时间将结束。 Accessing this array afterwards (through the returned pointer) is undefined behaviour. 之后(通过返回的指针)访问此数组是未定义的行为。
A simple solution would be to make d
a static
variable, such that its lifetime is will last until the program ends: 一个简单的解决方案是使
d
为static
变量,以使它的生存期一直持续到程序结束:
int* func() {
static int d[3];
But note that this variable d
will then exist only once in the program, such that the result of one call may be altered later. 但是请注意,该变量
d
在程序中仅存在一次,因此一个调用的结果可能会在以后更改。 Consider to use std::vector<int>
as return type or passing the array to be altered as function parameter void func(int[] d) {
考虑使用
std::vector<int>
作为返回类型,或将要更改的数组作为函数参数传递给void func(int[] d) {
Easiest workaround would be to use std::array (which is the prefered method) 最简单的解决方法是使用std :: array(这是首选方法)
#include <array>
std::array<int, 3> do_something() {
std::array<int, 3> arr = {1, 2, 3};
return arr;
}
int main() {
do_something()[0];
}
Best part about this is that the compiler will in-place construct this, meaning no performance was lost due to the copy. 最好的部分是编译器将就地构造它,这意味着不会因复制而损失性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.