[#0x0049] Const Pointer

1. 首先确定一点,int const i;与const int i;是一样的,都是定义一个只读的int i。

 

2. 所以int const *p;与const int *p;也是一样的,都是定义一个只读的int *p。

  但是,不管是int const *p;还是const int *p;,这里有几点需要注意。

#include <stdio.h>

int main() 
{
	int i1 = 30;
	int i2 = 40;
	const int *p = &i1;
	
	p = &i2; // no problem
	i2 = 80;
	printf("%d\n", *p); // output: 80
	
	// *p = 100; // error: assignment of read-only location
	
	return 0;
}

首先是*p只读,并不是p只读,所以p的值是可以改的(p = &i2;);第二,&i1应该只是一个int *,所以把一个int *赋值给const int *是可以的(const int *p = &i1;);第三,p = &i2;之后,对&i2这块地址的访问就有两种方式,一是非const的i2,二是const的*p,所以可以有i2 = 80;,而不能有*p = 100;

 

3. int * const p;是定义了一个只读的p,所以假如有int * const p = &i1;之后,就不能再有p = &i2;了。但是*p的值是可以随便改的。

 

4. 把一个const int *赋值给int *也是可以的(MinGW下)(int *p3 = &ci)

#include <stdio.h>

int main() 
{	
	const int ci = 200;
	int *p3 = &ci;
	
	*p3 = 250;
	printf("%d\n", *p3); // output: 250
	
	return 0;
}

这样其实是可以去修改一个const int的……

 

5. const int * const p;就是说p和*p都是只读的,结合2、3即可得它的特性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值