C++ 函数怎么返回数组?

文章导读
Previous Quiz Next C++ 不允许将整个数组作为函数的参数返回。然而,你可以通过指定数组名而不带索引来返回指向数组的 pointer。
A A

C++ 中从函数返回数组



Previous
Quiz
Next

C++ 不允许将整个数组作为函数的参数返回。然而,你可以通过指定数组名而不带索引来返回指向数组的 pointer。

如果你想从函数返回一个一维数组,你必须声明一个返回 pointer 的函数,如以下示例所示 −

int * myFunction() {
   .
   .
   .
}

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

现在,考虑以下函数,它将生成 10 个随机数并使用数组返回它们,并按以下方式调用此函数 −

#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 的 pointer。
   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