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


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

24469
3387
32665
12289
23541
25986
4555
7825
15889
24072
*(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值