#include<iostream>
using namespace std;
//函数声明
int * fun1();
int * fun2();
int * fun3(int * const buf); //buf 实际上是个传出参数,const表示buf的指向不能更改
void dispArr(int *arr ,int n);
const int arrlen = 10;
int main()
{
//方法一,返回局部变量的首地址
int * arr;
arr = fun1();
cout << "这是方法一" << endl;
//dispArr(arr, arrlen); //运行会报错
/*方法二,在函数内部通过new动态创建数组,
然后记得在main函数使用完数组后将其delete下*/
cout << "这是方法二" << endl;
int *arr1;
arr1 = fun2();
dispArr(arr1, arrlen);
delete arr1;
//方法三,由调用者自己申请缓存区和释放缓存区
cout << "这是方法三" << endl;
int *arr2 = new int[arrlen];
int *ret = fun3(arr2);
dispArr(arr2, arrlen);
delete arr2;
return 0;
}
//函数定义
int *fun1()
{
int temp[arrlen];
for (int i = 0; i < arrlen;++i)
{
temp[i] = i;
}
return temp;
}
int *fun2()
{
int *temp = new int[arrlen];
for (int i = 0; i < arrlen; i++)
{
temp[i] = i;
}
return temp;
}
int *fun3(int* const buf)
{
if(buf==NULL)
{
cerr<<"error: null ptr @buf"<<endl;
return NULL;
}
for(int i=0; i<arrlen; i++)
{
buf[i]=i;
}
return buf;
}
void dispArr(int* arr, int n)
{
for (int i = 0; i < n; i++)
{
cout << "arr" << "[" << i << "]" << " is:" <<arr[i]<<endl;
}
}
参考:https://www.cnblogs.com/walter-xh/p/6192800.html?ivk_sa=1024320u
https://www.runoob.com/cplusplus/cpp-return-arrays-from-function.html