uacs2024

导航

C++ 从函数返回指针

C++ 允许从函数返回指针,必须声明一个返回指针的函数:

int * myFunction()

C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 static变量。

 1 #include <iostream>
 2 #include <ctime>
 3 #include <cstdlib>
 4  
 5 using namespace std;
 6  
 7 // 要生成和返回随机数的函数
 8 int * getRandom( )
 9 {
10   static int  r[10];
11  
12   // 设置种子
13   srand( (unsigned)time( NULL ) );
14   for (int i = 0; i < 10; ++i)
15   {
16     r[i] = rand();
17     cout << r[i] << endl;
18   }
19  
20   return r;
21 }
22  
23 // 要调用上面定义函数的主函数
24 int main ()
25 {
26    // 一个指向整数的指针
27    int *p;
28  
29    p = getRandom();
30    for ( int i = 0; i < 10; i++ )
31    {
32        cout << "*(p + " << i << ") : ";
33        cout << *(p + i) << endl;
34    }
35    return 0; 36 }

运行结果:

624723190
1468735695
807113585
976495677
613357504
1377296355
1530315259
1778906708
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415

 

posted on 2024-03-01 20:23  ᶜʸᵃⁿ  阅读(13)  评论(0编辑  收藏  举报