[#0x0049] Const Pointer
1. 首先确定一点,int const i;与const int i;是一样的,都是定义一个只读的int i。
2. 所以int const *p;与const int *p;也是一样的,都是定义一个只读的int *p。
但是,不管是int const *p;还是const int *p;,这里有几点需要注意。
#include <stdio.h>
int main()
{
int i1 = 30;
int i2 = 40;
const int *p = &i1;
p = &i2; // no problem
i2 = 80;
printf("%d\n", *p); // output: 80
// *p = 100; // error: assignment of read-only location
return 0;
}
首先是*p只读,并不是p只读,所以p的值是可以改的(p = &i2;);第二,&i1应该只是一个int *,所以把一个int *赋值给const int *是可以的(const int *p = &i1;);第三,p = &i2;之后,对&i2这块地址的访问就有两种方式,一是非const的i2,二是const的*p,所以可以有i2 = 80;,而不能有*p = 100;
3. int * const p;是定义了一个只读的p,所以假如有int * const p = &i1;之后,就不能再有p = &i2;了。但是*p的值是可以随便改的。
4. 把一个const int *赋值给int *也是可以的(MinGW下)(int *p3 = &ci)
#include <stdio.h>
int main()
{
const int ci = 200;
int *p3 = &ci;
*p3 = 250;
printf("%d\n", *p3); // output: 250
return 0;
}
这样其实是可以去修改一个const int的……
5. const int * const p;就是说p和*p都是只读的,结合2、3即可得它的特性。