C++ 函式中返回指標



正如我們在上一章中看到的,C++ 允許從函式返回陣列,類似地,C++ 也允許您從函式返回指標。為此,您必須宣告一個返回指標的函式,如下例所示:

int * myFunction() {
   .
   .
   .
}

第二個需要記住的是,將區域性變數的地址返回到函式外部不是一個好主意,因此您必須將區域性變數定義為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
cpp_pointers.htm
廣告