1)const int *p
p是一个指向整型常量的指针,可以修改指针的值,但不能修改指针所指向的值
#include <stdio.h>
int main()
{
int b = 5;
int c = 3;
const int *p = &b;
printf("*p is %d\n",*p);
*p = 6;//错误,向只读位置 *p赋值
p = &c;//可以修改指针的值
printf("*p is %d\n",*p);
return 0;
}
2)int const * p
和1)中的用法相同,p是一个指向整型常量的指针
3)int * const p;
p是一个常指针,指针p是常量,它的值无法修改,但p指向的整型的值可以修改
#include <stdio.h>
int main()
{
int b = 5;
int c = 3;
int * const p = &b;
printf("*p is %d\n",*p);
*p = 6;//正确
p = &c;//错误,向只读变量p赋值
printf("*p is %d\n",*p);
return 0;
}
4)const int * const p
无论指针本身还是它所指向的值都是常量,不能修改
#include <stdio.h>
int main()
{
int b = 5;
int c = 3;
const int * const p = &b;
printf("*p is %d\n",*p);
*p = 6;//错误,向只读位置 *p赋值
p = &c;//错误,向只读变量p赋值
printf("*p is %d\n",*p);
return 0;
}
简单的辨别这几种用法的判断方法
沿着*号一条线,如果const位于*左侧,那么const就是用来修饰指针所指向的变量,即指针指向常量;
如果const位于*右侧,那么const就是用来修饰指针本身,即指针本身是常量。
这样是不是很好的就知道了const到底修饰谁了呢?大家也可以试试哈 ^_^