目录

从函数返回指针(Return Pointer from Functions)

正如我们在上一章中看到的,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
↑回到顶部↑
WIKI教程 @2018