指针常量和常量指针

参考自:《C和C++程序员面试秘籍》

指针常量:它本身不能被修改,指向的内容可以被修改。
常量指针:它本身可以被修改,指向的内容不能被修改。

const char *node1 = "abc";
char *const node2 = "abc";
char *node3 = "abc";

node1[2] = 'k';/*error: assignment of read-only location ‘*(node1 + 2u)’*/
*node1[2] = 'k';/*invalid type argument of unary ‘*’ (have ‘int’)*/
*node1 = "xyz";/*error: assignment of read-only location ‘*node1’*/
node1 = "xyz";/*ok*/

node2[2] = 'k';/*运行时错误*/
*node2[2] = 'k';/*error: invalid type argument of unary ‘*’ (have ‘int’)*/
*node2 = "xyz";/*warning: assignment makes integer from pointer without a cast [enabled by default]*/
node2 = "xyz";/*error: assignment of read-only variable ‘node2’*/

node3 = "xyz";/**/

node1和node2分别是常量指针和指针常量,一个不能修改内容,一个不能修改指向;而且它们在初始化时都指向了常量字符串“abc”,因此,它们对于指向内存的修改都是非法的。如果是对node1操作,会出现编译时错误;如果对node2操作,会出现运行时错误。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值