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

4.2.3.2指针转换为限定的对象类型

  C中,限定类型有const, volatilerestrict,例如,编译器隐式地转换任意指针为int,需要使用const int指针,如果你要删除掉限定词,就需要使用显式类型转换,如下例所描述:

    int n = 77;
    const int *ciPtr = 0;   // A pointer to const int.
                            // The pointer itself is not constant!
 
    ciPtr = &n;          // Implicitly converts the address to the type
                         // const int *.
 
    n = *ciPtr + 3;      // OK: this has the same effect as n = n + 3;
 
    *ciPtr *= 2;         // Error: you can't change an object referenced by
                         // a pointer to const int.
 
    *(int *)ciPtr *= 2;  // OK: Explicitly converts the pointer into a
                         // pointer to a nonconstant int.

本例中倒数第二行语句描述了为什么指向const类型的指针有时叫做只读指针,尽管你可以修改指针的值,但不能修改它们所指的对象。

4.2.3.3 Null指针常量

  Null指针常量为一个值为0的整型常量,或者是一个表示值0void指针,NULL宏定义在头文件stdlib.h中,表示一个null指针常量,下例描述了使用NULL宏初始化指针。

    #include <stdlib.h>

    long *lPtr = NULL;      // Initialize to NULL: pointer is not ready for use.

 

    /* ... operations here may assign lPtr an object address ... */

 

    if ( lPtr != NULL )

    {

      /* ... use lPtr only if it has been changed from NULL ... */

    }

当你将null常量指针转换为另一个指针类型,结果称为null指针,null指针的位模式不需要一定为0,然而,当你比较null指针和0,或NULL、或另一个null指针,结果通常为truenull指针与指向有效类型或函数的指针比较时,通常结果为false

posted @ 2011-01-23 19:39  Socrates  阅读(134)  评论(0编辑  收藏  举报