当前位置: 代码迷 >> 综合 >> c++从函数返回数组
  详细解决方案

c++从函数返回数组

热度:103   发布时间:2023-09-27 15:08:28.0

c++不允许返回一个完整的数组作为函数的参数,但是,用户可以通过指定不带索引的数组名来返回一个指向数组的指针

如果用户想要从函数返回一个一维数组,用户必须声明一个返回指针的函数,如下:

int * myFunction()

{

}

另外,c++不支持在函数外返回局部变量的地址,除非定义局部变量为static变量

实例:

#include <iostream>

#include <ctime>

using namespace std;

int *getRandom() //要生成和返回随机数的函数

{

static int r[10];

srand((unsigned)time(NULL));

for (int i=0;i<10;++i)

{

r[i]=rand();

cout<<r[i]<<endl;

}

return r

}

int main()

{

int *p;

p=getRandom();

for (int i=0;i<10;i++)

{

cout<<"*(p+"<<i<<"):";

cout<<*(p+i)<<endl;

}

return 0;

}

显示结果



  相关解决方案