您的位置:首页 > 其它

C核心技术手册(三十二)

2011-01-23 19:39 218 查看
4.2.3.2指针转换为限定的对象类型
在C中,限定类型有const,volatile和restrict,例如,编译器隐式地转换任意指针为int,需要使用constint指针,如果你要删除掉限定词,就需要使用显式类型转换,如下例所描述:
intn=77;

constint*ciPtr=0;//Apointertoconstint.

//Thepointeritselfisnotconstant!


ciPtr=&n;//Implicitlyconvertstheaddresstothetype

//constint*.


n=*ciPtr+3;//OK:thishasthesameeffectasn=n+3;


*ciPtr*=2;//Error:youcan'tchangeanobjectreferencedby

//apointertoconstint.


*(int*)ciPtr*=2;//OK:Explicitlyconvertsthepointerintoa

//pointertoanonconstantint.

本例中倒数第二行语句描述了为什么指向const类型的指针有时叫做只读指针,尽管你可以修改指针的值,但不能修改它们所指的对象。
4.2.3.3Null指针常量
Null指针常量为一个值为0的整型常量,或者是一个表示值0的void指针,NULL宏定义在头文件stdlib.h中,表示一个null指针常量,下例描述了使用NULL宏初始化指针。
#include<stdlib.h>
long*lPtr=NULL;//InitializetoNULL:pointerisnotreadyforuse.

/*...operationsheremayassignlPtranobjectaddress...*/

if(lPtr!=NULL)
{
/*...uselPtronlyifithasbeenchangedfromNULL...*/
}
当你将null常量指针转换为另一个指针类型,结果称为null指针,null指针的位模式不需要一定为0,然而,当你比较null指针和0,或NULL、或另一个null指针,结果通常为true,null指针与指向有效类型或函数的指针比较时,通常结果为false。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: