常量指针 和 指针常量

  在C++的学习中,有人经常搞不清楚“常量指针”和“指针常量”这两个概念。其实简单一点讲,“常量指针”所指向的地址上的数据是常量,而“指针常量”所指向的地址是常量,地址上面的数据是可以变化的。


     下面看及格简单的例子,可以说明他们的区别:
            第一个
 1  void  main(){
 2       char   * str1 = { " Hello " };
 3       char   * str2 = { " Hello World " };
 4       char   *   const  ptr1  = str1 ;
 5       // 指针常量--指针本身是常量,指向的地址不可以变化,但是指向的地址所对应的内容可以变化
 6 
 7      ptr1  = str2;  // 错误 因为这是一个常量指针,改变指向的地址了
 8 
 9      printf( " %s \n " , * ptr1);
10      }
11 
12 
13  //  编译错误    error C3892: 'ptr1' : you cannot assign to a variable that is const    
14 


</>第二个

 1  void  main(){
 2       char   * str1 = { " Hello " };
 3       char   * str2 = { " Hello World " };
 4       char   *   const  ptr1  = str1 ;
 5       // 指针常量--指针本身是常量,指向的地址不可以变化,但是指向的地址所对应的内容可以变化
 6 
 7       * ptr1  = ' A ' ; //  正确 因为指向的地址的内容是可以变化的
 8 
 9      printf( " %c \n " , * ptr1);
10      }
11 
12  // 输出  A
13 

第三个

 1  void  main(){
 2       char   * str1 = { " Hello " };
 3       char   * str2 = { " Hello World " };
 4       const   char   * ptr1  =  str1;
 5       // 常量指针--指向字符串常量,所指向的字符串内容不能变,但是指向的地址可以变化
 6      
 7      ptr1 = str2; //  正确 因为指向的地址是可以变化的
 8 
 9      printf( " %s \n " ,ptr1);
10      }
11 
12  // 输出 Hello World

第四个

 1  void  main(){
 2       char   * str1 = { " Hello " };
 3       char   * str2 = { " Hello World " };
 4       const   char   * ptr1  =  str2;
 5       // 常量指针--指向字符串常量,所指向的字符串内容不能变,但是指向的地址可以变化
 6      
 7      ptr1 = ' A ' ; //  错误 因为指向的地址是内容是不可以变化的
 8 
 9      printf( " %c \n " ,ptr1);
10      }
11 
12 
13  // 编译错误    error C2440: '=' : cannot convert from 'char' to 'const char *'
14 

相信从上面四个简单的例子可以看出他们不一样的地方把,在这里要请大家注意一下的地方是:

指针常量的申明:const 放在* 和指针名之间 Type * const pointer ;

常量指针的申明:const放在类型说明符之前 const Type *pointer ;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值