C核心技术手册(三十二)
2011-01-23 19:39
218 查看
4.2.3.2指针转换为限定的对象类型
在C中,限定类型有const,volatile和restrict,例如,编译器隐式地转换任意指针为int,需要使用constint指针,如果你要删除掉限定词,就需要使用显式类型转换,如下例所描述:
本例中倒数第二行语句描述了为什么指向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。
在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。
相关文章推荐
- C核心技术手册(三十二)
- 《Red5 用户参考手册》之十一:Red5 核心技术第四章 安全
- 《Red5 用户参考手册》之十二:Red5 核心技术第五章 脚本实现
- C核心技术手册(三十八)
- C核心技术手册(四十)
- C核心技术手册(四十三)
- C核心技术手册(二)
- C核心技术手册(五)
- C核心技术手册(二十二)
- C核心技术手册(二十八)
- C核心技术手册(三十一)
- 《Red5 用户参考手册》之九:Red5 核心技术第二章 将 Red5 部署到 Tomcat
- 《Red5 用户参考手册》之十一:Red5 核心技术第四章 安全
- C核心技术手册(四十)
- C核心技术手册(四十三)
- C核心技术手册(四十六)
- C核心技术手册(二)
- C核心技术手册(五)
- C核心技术手册(十六)
- C核心技术手册(三十一)