关于常量指针和指针常量

关于常量指针和指针常量

知乎上看到一篇关于这两个概念的理解,感觉挺通俗易懂的,在此记录一下。

①const int p;
②const int* p;
③int const* p;
④int* const p;
⑤const int* const p;
⑥int const* const p;
第一种是常量整数,没什么好说的。
后面五种是指针,有一个简便的办法记忆。
从右往左读,遇到p就替换成“p is a ”遇到*就替换成“point to”。
比如说
②读作:p is a point to int const. p是一个指向整型常量的指针。
③读作:p is a point to const int.意思跟②相同。
④读作:p is a const point to int.p是一个常量指针,指向整型。
⑤读作:p is a const point to int const.
⑥读作:p is a const point to const int.
⑤和⑥的意思相同,p都是常量指针,指向整型常量。

const int  ptr = 5;     // ptr为常量,初始化后不可更改,错误如:ptr = 6
const int* ptr = &a;    //*ptr为常量,不能通过*ptr改变它指向的内容,错误如:*ptr = 5
int const* ptr;         //*ptr为常量,同上
int* const ptr = &a;    // ptr为常量,初始化后不能再指向其它地址,错误如:ptr = &b
Reference

如何理解常量指针与指针常量?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值