来聊聊一个有点绕的问题:常指针;指向常量的指针;指向常量的常指针
先给声明:
const int *p -----> 指向常量的指针(指针指向的数据不能改变,但是指针可以指向其他数据)
int * const p -----> 常指针(指针不可变,即指针不能指向其他数据,指针目前指向的数据可被改变)
const int * const p -----> 指向常量的常指针(/*丧心病狂*/ 指针不可指向其他的数据,当前指向的数据亦不可被修改!)
tips:对于这种形式的声明,有个小技巧:把*读作pointer to,然后整个句子从后往前读。
那么const int *p 就可以 p is a pointer to const int ,翻译:p是一个指向const int 的指针,是不是瞬间明了了呢,
注意,这儿const int *p 和 int const *p是等价的,都是一个意思;
同理:int * const p ,可以读作:const p is a pointer to int
const int * const p可以读作:const p is a pointer to const int
还没完呢。。。(区分const int *p 和int * const p还有一个方法:
以*号为界线,const在*号右边,就是修饰指针变量,const在*号左边,就是修饰指针指向的数据)
其实,我们要知道,指针没什么神秘的,它也是一个变量,我们通常把指针理解为指向某一块数据,ok,接下来,coding 一下!!!
1、指向常量的指针:const int *p
如下图,p为指向常数据的指针,当对这块数据重新赋值时,编译出错,说明这块常数据不能修改,
但是,语句:a = 1;是可以的噢,毕竟a说:关我什么事,我只是一个变量啊!!
2、常指针:int * const p
常指针,顾名思义,就是该指针是常量,也就是说指针不能指向其他的数据了,要专一嘛。
3、指向常量的常指针:const int * const p
这个就是寸步难移了,啥也不能干,定义的这个指针呢,不能指向另外的数据,当前指向的数据也不能被修改!!