指针杂篇

来源:互联网 发布:代理服务器软件 开源 编辑:程序博客网 时间:2024/05/16 00:31

1、返回指针(数组首地址)的函数中,因为C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 static 变量。所以代码如下:

#include <iostream>#include <ctime>#include <cstdlib>using namespace std;// 要生成和返回随机数的函数int * getRandom( ){  static int  r[10];//注意把这个数组定义为static类型。  // 设置种子  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;}

2、

常量引用

int i = 42;  const int &r1 = i;cout<<r1;

这个 输出的是i里面的值,42。

常量指针

int i = 42;  const int *ptr;ptr=&i;

需要通过:

cout<<*ptr;

来输出