1 #include<stdio.h> 2 void main(){ 3 int a = 1; 4 int const *p1;//指向常量的指针 5 const int *p2;//指向常量的指针 6 p1 = &a; 7 p2 = &a; 8 *p1 = 2;//企图改变a的值(非法) 9 *p2 = 2;//企图改变a的值(非法) 10 11 int * const b;//常量指针(常指针) 12 b = &a;//企图改变b的值。(非法) 13 }
编译结果:
hello.c: In function ‘main’: hello.c:8:2: error: assignment of read-only location ‘*p1’ *p1 = 2;//企图改变a的值(非法) ^ hello.c:9:2: error: assignment of read-only location ‘*p2’ *p2 = 2;//企图改变a的值(非法) ^ hello.c:12:2: error: assignment of read-only variable ‘b’ b = &a;//企图改变b的值。(非法) ^
区分技巧:
首先两者都是指针。看*和const谁离的变量名近:如果const近,那么就是const指针(const=常量嘛,常指针);如果*近,就是指向常量的指针,此时const与int的位置无关。