C语言中的const指针
来源:互联网 发布:gtv网络棋牌频道如何看 编辑:程序博客网 时间:2024/05/22 06:48
最近复习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
- C语言中的const指针
- C语言中的const与指针
- C语言中的一些诡异事件 const malloc 指针
- C语言中的const与指针的同址异值现象(指针究竟能不能修改const问题)
- C语言中的const
- C语言中的const
- C语言中的const
- C语言中的const
- C语言中的const
- c语言初学-const指针
- const和指针(C语言)
- c语言-指针 const解析
- C语言const与指针
- C语言--const和指针
- C语言中的const用法以及常量指针与指针常量(有口诀!)
- C语言中的CONST使用
- C 语言中的const 解析
- 详解C语言中的const
- Android移植之WIFI
- mongodb指南(二十) - developer zone - 索引(四)地理信息索引
- 四极管 Windows CE 5.0 数据类型大全
- 最近停止更新日志了
- ubuntu 10.04 安装JDK
- C语言中的const指针
- mongodb指南(二十一) - developer zone - 索引(五)在后台创建索引
- Windows下Android的源码下载
- 趣味算法-Hanoi
- mongodb指南(二十二) - developer zone - 索引(六)多键
- web门户登录成功校验LR脚本(web_reg_find应用)
- 非托管界面可以使用ADO.NET.
- 使用MPMoviePlayerController播放视频
- Ubuntu下的源码下载及编译