c++学习笔记(七):函数返回数组

来源:互联网 发布:计算机三级数据库 编辑:程序博客网 时间:2024/06/06 02:59

C++不允许返回整个数组作为参数传递给函数。但是,可以通过指定数组名不带索引返回一个指针数组。

如果想从一个函数返回一个一维数组,就必须声明返回一个指针,在下面的例子中的函数:

int * myFunction(){...}

第二点要记住的是,C++不提倡给本地变量的地址返回在函数之外,所以必须定义局部变量为静态变量。

现在,考虑下面的函数,这将产生10个随机数字并使用数组返回它们,并调用这个函数如下:

#include <iostream>#include <ctime>using namespace std;// function to generate and retrun random numbers.int * getRandom( ){  static int  r[10];  // set the seed  srand( (unsigned)time( NULL ) );  for (int i = 0; i < 10; ++i)  {    r[i] = rand();    cout << r[i] << endl;  }  return r;}// main function to call above defined function.int main (){   // a yiibaier to an int.   int *p;   p = getRandom();   for ( int i = 0; i < 10; i++ )   {       cout << "*(p + " << i << ") : ";       cout << *(p + i) << endl;   }   return 0;}

当上述代码被编译在一起并执行时,它会产生导致一些如下:

62472319014687356958071135859764956776133575041377296355153031525917789067081820354158667126415*(p + 0) : 624723190*(p + 1) : 1468735695*(p + 2) : 807113585*(p + 3) : 976495677*(p + 4) : 613357504*(p + 5) : 1377296355*(p + 6) : 1530315259*(p + 7) : 1778906708*(p + 8) : 1820354158*(p + 9) : 667126415

0 0
原创粉丝点击