【C++】指针(6):从函数返回指针
2017-02-03 18:51
387 查看
C++ 从函数返回指针
我们已经了解了 C++ 中如何从函数返回数组,类似地,C++ 允许您从函数返回指针。为了做到这点,您必须声明一个返回指针的函数,如下所示:int * myFunction() { . . . }
另外,C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 static 变量。
现在,让我们来看下面的函数,它会生成 10 个随机数,并使用表示指针的数组名(即第一个数组元素的地址)来返回它们,具体如下:
#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; }
当上面的代码被编译和执行时,它会产生下列结果:
624723190 1468735695 807113585 976495677 613357504 1377296355 1530315259 1778906708 1820354158 667126415 *(p + 0) : 624723190 *(p + 1) : 1468735695 *(p + 2) : 807113585 *(p + 3) : < b4d4 span class="lit" style="border:0px;margin:0px;padding:0px;color:rgb(0,102,102);">976495677 *(p + 4) : 613357504 *(p + 5) : 1377296355 *(p + 6) : 1530315259 *(p + 7) : 1778906708 *(p + 8) : 1820354158 *(p + 9) : 667126415
相关文章推荐
- C++中返回指向函数的指针
- C/C++函数返回二维数组指针问题
- 【C++】指针作为函数的返回值
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- c++中函数中变量内存分配以及返回指针、引用类型的思考
- [C/C++]如何解读返回函数指针的函数声明
- c/c++使用指针做函数返回值和指针作函数参数问题
- c++函数内部可以返回函数内部定义的指针 但是不能返回函数内部定义的数组
- C/C++—— 写一个函数,它的参数为指向函数的指针,返回类型也为指向函数的指针
- C++函数返回局部变量指针的问题
- C++中返回指向函数的指针学习
- 【C++总结】函数形参,返回const对象与非const对象,成员函数,函数指针
- [C++] C++中const修饰指针,变量, 函数参数和函数返回值的用法总结
- 条款31: 千万不要返回局部对象的引用,也不要返回函数内部用new初始化的指针的引用 (转自effective c++ second edition)
- C/C++函数返回数组指针的一点点小姿势
- 对C++中指针做函数返回值的认识
- 【C++】指向函数的指针与返回指针的函数
- Self Summary: C++函数返回引用和指针的问题,局部对象与new对象的问题
- c++返回指针的函数应用于求素数的实例
- C++学习记录之函数返回值为指针的问题