const int *p与int *const p的区别

来源:互联网 发布:彻底掌握c语言 编辑:程序博客网 时间:2024/05/21 17:52

转载于:http://blog.csdn.net/suer0101/article/details/8032269


本文只是一篇学习笔记,是看了《彻底搞定C指针》中的相关篇幅后的一点总结,仅此而已!

一、先搞清const int *p与int const *p的区别

它们的区别就是:没有区别!!

无论谁在前面都没有影响!所以const int *p与int const *p用法一样!


二、const int *p的用法

[cpp] view plaincopy
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4.   
  5. int main(int argc, char **argv)  
  6. {  
  7.     int test1 = 1;  
  8.     int test2 = 2;  
  9.     const int *p;  
  10.       
  11.     p = &test1;  
  12.     p = &test2;  
  13.     test2 = 3;  
  14.     //*p = 4;     error: assignment of read-only location ‘*p’  
  15.     printf("%d\n", *p);  
  16.       
  17.     return 0;  
  18. }  

执行结果 :3 ,这个好理解,如果加入被我注释掉的那一行就会报错,编译通不过,我用的是gcc version 4.4.3。也就是说*p是常量,不可更改,但指针p还是变量,你想怎么 变都可以。


三、int *const p的用法

[cpp] view plaincopy
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4.   
  5. int main(int argc, char **argv)  
  6. {  
  7.     int test1 = 1;  
  8.     int test2 = 2;  
  9.     int *const p = &test1;  //只能在声明的时候就给它赋初值,否则还是会报错的  
  10.   
  11.     //p = &test2;           error: assignment of read-only location ‘*p’  
  12.     test1 = 3;  
  13.     printf("%d\n", *p);  
  14.       
  15.     return 0;  
  16. }  
执行结果 :3 ,这样用p是常量,也就是说p所指向的地址是不可以更改的,所以当把test2的地址赋值给p时就会报错!但是p所指的地址内容是可以改变的。

三、补充const int *const p

[cpp] view plaincopy
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4.   
  5. int main(int argc, char **argv)  
  6. {  
  7.     int test1 = 1;  
  8.     int test2 = 2;  
  9.     const int *const p = &test1;  
  10.   
  11.     //p = &test2;  
  12.     //*p = 3;  
  13.     printf("%d\n", *p);  
  14.       
  15.     return 0;  
  16. }  
执行结果 :1,这个就相当于以上两种情况的混合体,p是常量,所以不能把test2的地址赋给p;同时*p也是常量,所以*p的内容不可更改!
0 0
原创粉丝点击