C++---从函数返回指针

来源:互联网 发布:淘宝网商贷额度没了 编辑:程序博客网 时间:2024/06/05 21:16


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

#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;}
当上面的代码被编译和执行时,它会产生下列结果:

24469338732665122892354125986455578251588924072*(p + 0) : 24469*(p + 1) : 3387*(p + 2) : 32665*(p + 3) : 12289*(p + 4) : 23541*(p + 5) : 25986*(p + 6) : 4555*(p + 7) : 7825*(p + 8) : 15889*(p + 9) : 24072

转载来自:http://www.runoob.com/cplusplus/cpp-return-pointer-from-functions.html

0 0
原创粉丝点击