如何从C++函数中返回局部变量
下文讨论在函数中返回创建的局部变量的方式,可以通过将调用函数返回指向该变量的指针来实现。
尝试以常规方式返回局部变量时会发生什么?
例如,在以下代码中,当数组在函数内部创建并返回到调用者函数时,会抛出运行时错误,因为数组在堆栈内存中创建,因此一旦函数终止,它就被删除了。
#include <bits/stdc++.h>
using namespace std;
// Function to return an
// array
int* fun()
{
int arr[5] = { 1, 2, 3, 4, 5 };
return arr;
}
// Driver Code
int main()
{
int* arr = fun();
// 会导致错误
cout << arr[2];
return 0;
}
输出
Segmentation Fault (SIGSEGV)
如何从函数返回局部变量?
但是,可以通过使用指针访问函数的局部变量,通过创建指向将要返回的变量的另一个指针变量并返回指针变量本身来实现。
- 返回局部变量:
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return
// a pointer
int* fun()
{
int x = 20;
int* ptr = &x
return ptr;
}
// Driver Code
int main()
{
int* arr = fun();
cout << *arr;
return 0;
}
输出
20
注意: 在这里,指针有效是因为普通变量存储在堆栈中,在函数结束后被销毁。但是,指针存储在堆中,并且即使fun调用结束,它们仍然保留。因此,我们可以访问该值。
- 返回数组:
#include <bits/stdc++.h>
using namespace std;
// Function to return an
// array
int* fun()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
return ptr;
}
// Driver Code
int main()
{
int* arr = fun();
cout << arr[2];
return 0;
}
输出
3