C++ 函数返回指针注意事项

来源:互联网 发布:制作pe的软件 编辑:程序博客网 时间:2024/05/29 08:27

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;}
将局部变量变成static变量,返回才能成功!