C++ 中函式返回陣列



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 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
廣告