本文共 1575 字,大约阅读时间需要 5 分钟。
const int * grape;int const * grape;int * const grape_jelly;
The last of these cases makes the pointer read-only, whereas the other two make the object that it points at read-only; and of course, both the object and what it points at might be constant. Either of the following equivalent declarations will accomplish this:
const int * const grape_jam;int const * const grape_jam;
关键问题点:const 属于修饰符 ,关键是看const 修饰的位置在那里
这里const 修饰的是int,而int定义的是一个整值
因此*a 所指向的对象 值 不能通过 *a 来修改,但是 可以重新给 a 来赋值,使其指向不同的对象 eg:const int *a = 0;const int b = 1;int c = 1;a = &b //ok! 额外:注意不能通过a 来修改 b值a = &c //ok! 额外:虽然c本身不是一个常量*a = 2 //erro! 为题就在这里,不能修改通过 *a 所指向的对象值,最后赋值得对象是c,因此不能通过*a 来修改c值。
这里const修饰的是 a ,a代表的是一个指针地址,因此不能赋给a其他的地址值,但可以修改a指向的值,这有点和cont int *a相反的意味。
#includeint main(){ int b = 1; int c = 3; int *const a = &b; *a = 2; printf("*a = %d\n", *a); a = &c; //错误:向只读变量‘a’赋值 return 0;}
和 const int *a 的意义是相同的 他们两个的作用等价
#includeint main(){ int b = 1; int c = 3; const int *a = &b; int const *d = &c; *a = 2;//错误:向只读位置‘*a’赋值 b = 2;//正确 printf("*a = %d\n", *a); *d = 4;//错误:向只读位置‘*d’赋值 c = 4; printf("*d = %d\n", *d); return 0;}
这个代表a所指向的对象的值以及它的地址本身都不能被改变
关于const的点滴补充:转载地址:http://lbtaf.baihongyu.com/