const和指针

1·非常量数据的非常量指针 
定义:int *ptr; 
举例说明: 
#include <stdio.h> 

//非常量数据的非常量指针指向的内存地址和存储的内容都可以改变! 
int main() 

int a = 100; 
int b = 200; 
int *ptr = &a ; 

*ptr = b; //合法 
ptr = &b; //合法 
return 0; 


2·常量数据的非常量指针 
定义:const int *ptr; 
举例说明: 
#include <stdio.h> 

//常量数据的非常量指针指向的内存地址可以改变但是存储的内容不可以改变! 
int main() 

const int a = 100;//定义一个常量数据 
int b = 200; 
const int *ptr = &a ;//指向一个常量数据的非常量指针 
//这时候表示指针指向的内存地址可以改变,但是地址里面储存的内容不能改变! 
ptr = &b; //合法 
*ptr = b; //非法! 
//VC++6.0编译结果:error C2166: l-value specifies const object 
//把光标移到编译这条编译信息里,按F1,可以看看MSDN关于这条编译错误的定义 
return 0; 


3·非常量数据的常量指针 
定义:int * const ptr; 
举例说明: 
#include <stdio.h> 

//非常量数据的常量指针指向的内存地址不可以改变但是存储的内容可以! 
int main() 

int a = 100; 
int b = 200; 
int * const ptr = &a;//这里一旦指向一个固定的地址以后就不可以再改变了 
//但是地址里面存放的内容依然可以改变 
ptr = &b; //非法! 
*ptr = b; //合法 

return 0; 


4·常量数据的常量指针 
定义:const int * const ptr; 
举例说明: 
#include <stdio.h> 

//常量数据的常量指针指向的内存地址和存储的内容都不可改变! 
int main() 

const int a = 100; 
int b = 200; 
const int * const ptr = &a; 

ptr = &b; //非法! 
*ptr = b; //非法! 

return 0; 


以上代码均在VC++6.0上测试过。 
注意:可能有些编译器不支持const!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值