C++中指针笔记

博客主要讲解了C++中指针与常量的关系。指出answer_ptr指向的数据是常量不可变,但指针本身可变;若const在*后,指针是常量不可变,指向的数据可变;还提到将const放在两处,指针和指向的数据都不可变,并给出记忆方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The declaration:
const char *answer_ptr = "Forty-Two";

does not tell C++ that the variable answer_ptr is a constant. Instead it tells C++ that the data pointed to by answer_ptr is a constant. The data cannot be changed, but the pointer can. Again we need to make sure we know the difference between "things" and "pointers to things."

What's answer_ptr? A pointer. Can it be changed? Yes, it's just a pointer. What does it point to? A const char array. Can the data pointed to by answer_ptr be changed? No, it's constant.

If you put the const after the *, you tell C++ that the pointer is constant. For example:

char *const name_ptr = "Test";

What's name_ptr? A constant pointer. Can it be changed? No. What does it point to? A character. Can the data we pointed to by name_ptr be changed? Yes.

Finally, we put const in both places, creating a pointer that cannot be changed to a data item that cannot be changed:

const char *const title_ptr = "Title";

One way of remembering whether the const modifies the pointer or the value is to remember that *const reads "constant pointer" in English.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值