C++ 允许函数返回指针,需要声明返回指针的函数。
声明函数返回指针方式:
type *Function()
{
}
程序示例:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int *getRandom( )
{
static int arr[5];
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 5; ++i)
{
arr[i] = rand();
cout << arr[i] << endl;
}
return arr;
}
int main ()
{
int *p;
p = getRandom();
for ( int i = 0; i < 5; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
输出结果: