目录

从函数返回数组(Return array from functions)

C ++不允许将整个数组作为参数返回给函数。 但是,您可以通过指定不带索引的数组名称来返回指向数组的指针。

如果要从函数返回单维数组,则必须声明一个返回指针的函数,如下例所示 -

int * myFunction() {
   .
   .
   .
}

要记住的第二点是C ++不主张将局部变量的地址返回到函数外部,因此您必须将局部变量定义为static变量。

现在,考虑以下函数,它将生成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 pointer to an int.
   int *p;
   p = getRandom();
   for ( int i = 0; i < 10; i++ ) {
      cout << "*(p + " << i << ") : ";
      cout << *(p + i) << endl;
   }
   return 0;
}

当上面的代码一起编译并执行时,它产生的结果如下 -

624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(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
↑回到顶部↑
WIKI教程 @2018