C语言基础---const常指针的使用

有一个面试题:

http://blog.csdn.net/tigerjibo/article/details/6827809

1、解释下面ptr含义和不同(好像是。。。。题干了大概意思是这样。下面应该没错)

double* prt = &value

const double* ptr = &value

double* const ptr=&value

const double* const ptr=&value

2、去掉const属性,例:

      const double value = 0.0f;

      double* ptr = NULL;

怎么才能让ptr指向value?


#include<stdio.h>
/*void fun()
{
	extern const int a=10;//error C2205: cannot initialize extern variables with block scope
}*/
int main()
{
	const int a=10;
	int i=20;

	/*几种声明方式*/
	const int * b=&a;//b是指向常量a的指针
	int const * c=&a;//c与b一致 声明方式不同
	int * const d=&i;//d指向整型的常指针
	const int * const e=&a;

	/*
	 将const值赋值给非const指针: 
		C++:int * ptr = const_cast(&r);
		C语言使用:int * ptr =(int*)&r; 
	*/
	int * f=NULL;//空地址用 NULL	
	f=(int*)&a; //只能强制转换
	*f=20;//将常量赋值给非const指针会改变常量的值,表面上
	/* 
	some tests:
		b=0;//it's ok
		
		&a=0;//不能改变内存地址 readonly? error C2106: '=' : left operand must be l-value
		
		d=0;//error C2166: l-value specifies const object
	*/
	printf(" a:%d\n addrOfa:%d\n b:%d\n c:%d\n d:%d\n e:%d\n f:%d\n fake a:%d\n a:%d\n",a,&a,b,c,d,e,f,*f,a);
	return 0;
}

结果:

 a:10
 addrOfa:1244996
 b:1244996
 c:1244996
 d:1244992
 e:1244996
 f:1244996
 fake a:20
 a:10
Press any key to continue

更多应用:http://developer.51cto.com/art/201002/182348.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值