关于const修饰指针
2016-11-26 13:30
197 查看
基本的指针
int i = 0; int *p = &i; printf("%d\n",*p);
输出是0,指针p可以随意操作
const在*左边(左定值)
int i = 0; const int *p = &i; int const *q = &i; printf("%d %d\n",*p,*q); int temp = 2; p = &temp; printf("%d %d\n",*p,*q); *p = temp;
第一个printf输出0 0 ,第二个printf输出2 0,最后一行编译错误
当const在*左边的时候,指针所指向的值为只读属性,但是指针是可以指向其他地址的
const在*右边(右定向)
int i = 0; int * const p = &i; printf("%d\n",*p); int temp = 2; *p = 1; printf("%d %d\n",*p,i); p = &temp;
第一个printf输出0,第二个printf输出1 1,最后一行编译错误
当const在*右边的时候,指针不可以改变指向,但是最初指向的变量不是只读属性,可以更改里面的值
混合使用(又定值又定向)
int i = 0; const int * const p = &i; printf("%d\n",i); int temp = 2; p = &temp; *p = 2;
之前两种结合,最后两行都会报错
当混合使用的时候,指针p又定值又定向
相关文章推荐
- 关于const修饰指针
- 关于const 修饰变量、引用、指针的说明
- 关于const修饰指针
- 关于const修饰指针的问题
- 程序员面试(3):关于const修饰指针的情况
- 关于const修饰指针的情况
- C:带有const修饰的指针解读
- 关于函数指针的调用约定修饰
- 总结函数的参数,指针参数及const修饰的情况
- 关于C、C++中的const和指针
- C++中const修饰指针探讨
- 关于const与指针搭配使用的一点记录
- const 修饰 指针
- C++点滴——const/volatile不能用来修饰没有this指针的成员函数
- 关于const和指针的专题
- 关于const和指针的专题
- 关于const限定的字符指针
- const修饰指针和引用释疑
- 理解性记忆const修饰普通变量和指针的新思路
- const修饰指针