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