[root@bogon C++]# g++ test_array_function.cpp -o test_array_function
test_array_function.cpp: 在函数‘int* getRandom()’中:
test_array_function.cpp:12:33: 错误:‘srand’在此作用域中尚未声明
srand( (unsigned)time( NULL ) );
^
test_array_function.cpp:15:17: 错误:‘rand’在此作用域中尚未声明
r[i] = rand();
解决方案:
增加:#include <cstdlib>
C++中头文件cstdlib是是C++的函数库, 等价于C中的<stdlib.h>。可以提供一些类型、函数与常量:
1、类型:size_t, wchar_t, div_t, ldiv_t, lldiv_t。
2、常量:NULL, EXIT_FAILURE, EXIT_SUCCESS, RAND_MAX, MB_CUR_MAX。
3、函数:calloc()、free()、malloc()、realloc()、rand()、atoi()、atol()、rand()、srand()、exit()。
[root@bogon C++]# cat test_array_function.cpp
#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;
}
[root@bogon C++]#
[root@bogon C++]# g++ test_array_function.cpp -o test_array_function
[root@bogon C++]# ./test_array_function
342705179
1735631723
1884932714
1409631640
1175186931
1046409182
1148664731
1778548432
628655475
627766212
*(p + 0) : 342705179
*(p + 1) : 1735631723
*(p + 2) : 1884932714
*(p + 3) : 1409631640
*(p + 4) : 1175186931
*(p + 5) : 1046409182
*(p + 6) : 1148664731
*(p + 7) : 1778548432
*(p + 8) : 628655475
*(p + 9) : 627766212