对于指针和常量,有以下三种形式都是正确的:
const char * myPtr = &char_A;//指向常量的指针 char * const myPtr = &char_A;//常量的指针 const char * const myPtr = &char_A;//指向常量的常量指针
下面依次对这三种类型进行介绍。
因为*操作符是左操作符,左操作符的优先级是从右到左,对于
1.常量指针(Constant Pointers)
int * const p
先看const再看* ,是p是一个常量类型的指针,不能修改这个指针的指向,但是这个指针所指向的地址上存储的值可以修改。
实例1:
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
#include<iostream> #include<stdlib.h> using namespace std; void main() { int i1=30; int i2=40; int * const pi=&i1;//这里的pi指针式常量。 //pi=&i2; //注意这里,pi不能再这样重新赋值了,即不能再指向另一个新地址。所以我已经注释了它。 printf("%d\n", *pi ) ; //输出是30 i1=80; //5.想想看:这里能用*pi=80;来代替吗?可以,这里可以通过*pi修改i1的值。 printf("%d\n", *pi ) ; //输出是80 system("pause"); }
实例2:
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
char char_A = 'A'; char char_B = 'B'; char * const myPtr = &char_A; myPtr = &char_B; // error - can't change address of myPtr
2.指向常量的指针(Pointers to Constants)
const int *p
先看*再看const,定义一个指针指向一个常量,不能通过指针来修改这个指针指向的值。
实例3:
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
#include<iostream> #include<stdlib.h> using namespace std; void main() { int i1=30; int i2=40; const int * pi=&i1; printf("%d\n", *pi ) ; //输出是30 pi=&i2; //注意这里,pi可以在任意时候重新赋值一个新内存地址 i2=80; //想想看:这里能用*pi=80;来代替吗?当然不能 printf("%d\n", *pi ) ; //输出是80 system("pause"); }
实例4
char char_A = 'A'; const char * myPtr = &char_A; *myPtr = 'J'; // error - can't change value of *myPtr
所以指针p所指向的整型数是一个常量,其值不能被修改。