分享

C语言中的const指针

 心不留意外尘 2016-06-15

http://blog.csdn.net/edwzhang/article/details/7221638

2012

最近复习C,看到指针。记录一下这个const的用法。

 

测试代码:

#include <stdio.h>

int main() {

 int a = 100, b = 200;

 const int *p = &a;
 int * const q = &b;

 printf("a=%d, *p=%d\n", a, *p);
 printf("b=%d, *q=%d\n", b, *q);

 p = &b;
 //q = &a;
 printf("*p = %d\n", *p);

 //*p = b;
 *q = 888;


 printf("*q = %d\n", *q);

 return 0;
}

 

测试结果:

a=100, *p=100
b=200, *q=200
*p = 200
*q = 888

解释如下:

const int *p = &a;

此句,因为const写在int *的前面,表示不可以利用p指针间接改变a变量值,如: *p = 1,但是可以改变p指针指向另一个变量,如: p = &b。

 

int * const q = &b;

此句,因为const写在q的前面,表示不可以指定另一个变量的地址给q指针,如: q = &a,但是可以改变*q的值,如: *q = 2。

 

要是有如下语句:

const int * const p = &a;

表示不能通过*p间接改变变量a的值,也不能再指定另一个变量的地址给p指针。

 

要是放开上面代码中的两个注释,编译的时候报错:

../test.c: In function ‘main’:
../test.c:21: error: assignment of read-only variable ‘q’
../test.c:24: error: assignment of read-only location

 

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多