一,直接返回指针,开辟在栈区
C++中函数返回一个变量是很简单的,但C++函数的返回类型没有“数组”这一结构,所以返回数组我们通常需要使用指针指向数组的内存首地址来取得,就像这样,这样实际上是将变量开辟在了栈区:
#include <iostream>
// prototype
int * function1(int num1, int num2);
int main() {
using namespace std;
int * num_ptr = function1(1, 2);
cout << *num_ptr << " " << * (num_ptr + 1) << endl; // 输出内容
cout << num_ptr << endl; // 输出内存地址
return 0;
}
int * function1(int num1, int num2) {
using namespace std;
int num[] = {num1, num2};
// 创建赋值返回
int * ptr = &num[0];
return ptr;
}
输出:
/Users/CPP_Environment/CLionProjects/Cpp_project2/cmake-build-debug/Cpp_project2
1 1
0x16fdc3530
Process finished with exit code 0
我们发现输出不正常,理论上来说* (ptr + 1)输出的应该是2啊,这是因为第二次打印输出时,C++已经回收了该局部变量,原先的地址中存储的值已经不再是2。因此如果希望返回变量的地址,应该将该变量开辟在堆区。也就是使用new和delete进行动态内存管理:
二,使用new和delete动态管理内存,开辟在堆区
#include <iostream>
// prototype
int * function1(int num1, int num2);
int main() {
using namespace std;
int * num_ptr = function1(1, 2);
cout << *num_ptr << " " << num_ptr[1] << endl; // 输出内容
cout << num_ptr << endl; // 输出内存地址
delete[] num_ptr;
return 0;
}
int * function1(int num1, int num2) {
using namespace std;
int num[] = {num1, num2};
int * ptr = new int[2];
for (int i = 0; i < 2; i++) {
ptr[i] = num[i];
}
return ptr;
}
输出:
/Users/CPP_Environment/CLionProjects/Cpp_project2/cmake-build-debug/Cpp_project2
1 2
0x6000037bc020
Process finished with exit code 0
发现输出正常了,输出的时候使用*ptr和ptr[0]都可以了,要注意的是在最后要delete一下指针,否则可能发生内存泄露。