C++ 从函数返回指针

C++ 指针

在上一章中,我们已经了解了 C++ 中如何从函数返回数组,类似地,C++ 允许您从函数返回指针。为了做到这点,您必须声明一个返回指针的函数,如下所示:

int * myFunction()
{
.
.
.
}

另外,C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 static变量。

现在,让我们来看下面的函数,它会生成 10 个随机数,并使用表示指针的数组名(即第一个数组元素的地址)来返回它们,具体如下:

实例

#include <iostream>
#include <ctime>
#include <cstdlib>
 
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 *p;
 
   p = getRandom();
   for ( int i = 0; i < 10; i++ )
   {
       cout << "*(p + " << i << ") : ";
       cout << *(p + i) << endl;
   }
 
   return 0;
}

当上面的代码被编译和执行时,它会产生下列结果:

13129
32055
19374
8111
22762
29489
24935
29394
12501
19635
*(p + 0) : 13129
*(p + 1) : 32055
*(p + 2) : 19374
*(p + 3) : 8111
*(p + 4) : 22762
*(p + 5) : 29489
*(p + 6) : 24935
*(p + 7) : 29394
*(p + 8) : 12501
*(p + 9) : 19635

C++ 指针