C/C++中一个函数只能返回一个值,即使用 return + object
的方式。但是怎么返回一个数组呢?
一个代码块执行完之后,其中的对象是要被释放掉的,所以不能以返回局部变量的方式来返回数组。
可以通过使用new
运算符来申请动态内存,把数组写入到这个内存中,然后返回这个内存的首地址。
1 测试代码如下:
#include<iostream>
#include<cstdlib>
int* arr()
{
int *b = new int[3];
b[0] = 0;
b[1] = 1;
b[2] = 2;
return b;
}
int main(int argc, char const *argv[])
{
int *c = arr();
for(int i = 0; i < 3; i++)
std::cout<<c[i]<<std::endl;
delete[] c;
c = NULL;
system("pause");
return 0;
}
运行结果:
0
1
2
请按任意键继续. . .
第16行的delete[] c;
是清理函数int* arr()
中申请的内存。
还是同样的道理,只不过是使用结构体去实现,考虑了数组的长度问题。
2 代码如下:
#include<iostream>
#include<cstdlib>
struct sss
{
int length;
int *array;
};
sss* arr()
{
sss *s = new sss;
s->length = 5;
s->array = new int[s->length];
for(int i = 0; i < 5; i++)
s->array[i] = i;
return s;
}
int main(int argc, char const *argv[])
{
sss *c = arr();
for(int i = 0; i < c->length; i++)
std::cout<<c->array[i]<<std::endl;
delete c;
c = NULL;
system("pause");
return 0;
}
输出的结果为:
0
1
2
3
4
请按任意键继续. . .
但是由于在函数中使用动态内存的方法无法在函数体之内进行内存释放(如果释放内存,则无法返回数组),所以最好的方法是在函数体之外先申请好内存,这时在函数体外我们是知道申请好的内存的首地址和内存中可以存放的数组的长度的。我们可以把首地址和长度传递给函数,让这个函数把数组放到内存中,这样就可以在函数体之外申请内存并在函数体之外释放内存,好处是这两个过程可以成对出现,比较好看。
3 代码如下:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
int* func(int arr[],int length)
{
for(int i = 0; i < length; i++)
arr[i] = i;
return arr;
}
int main(int argc, char const *argv[])
{
int *arr = new int[10];
arr = func(arr,10);
for(int j = 0; j < 10; j++)
cout<<arr[j]<<" ";
delete[] arr;
system("pause");
return 0;
}
结果为:
0 1 2 3 4 5 6 7 8 9 请按任意键继续. . .