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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27278957/article/details/78032346

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变量,返回才能成功!

猜你喜欢

转载自blog.csdn.net/qq_27278957/article/details/78032346