C/C++语言返回数组的方法

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 请按任意键继续. . .
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值