怎么返回值为一个数组

来源:百度知道 编辑:UC知道 时间:2024/05/27 06:22:06
int[] subAry(int a1,int a2){
int[] subAry=new int[a2-a1];
int n,i;
for(n=0;n<(a2-a1);n++){
subAry[n]=m_ary[a1];
a1++;
}
return??????

}

这是不行的,但是你可以返回一个指针,该指针指向数组的首地址

#include "stdafx.h"
#include <iostream>
using namespace std;

#define N 5//指定数组的维数

int *p()//定义一个数组指针,返回值是指针
{
int *arr=new int[N];//这里用new的话必须确定数组维数
for (int i=0;i<N;i++)
{
arr[i]=i;//给数组赋值
}
return arr;//返回指向数组的的首地址
}

int _tmain(int argc, _TCHAR* argv[])
{
int *ptr=p();
for (int i=0;i<N;i++)
{
cout<<ptr[i]<<endl;
}
delete [] ptr;
system("pause");
return 0;
}
VS2008 下通过