设为首页 加入收藏

TOP

2.3 Compound Types (6)
2013-10-07 16:18:29 来源: 作者: 【 】 浏览:72
Tags:2.3 Compound Types

Other Pointer Operations

So long as the pointer has a valid value, we can use a pointer in a condition. Just as when we use an arithmetic value in a condition (§ 2.1.2, p. 35), if the pointer is 0, then the condition is false:

  1. int ival = 1024;   
  2. int *pi = 0; // pi is a valid, null pointer   
  3. int *pi2 = &ival; // pi2 is a valid pointer that holds the address of ival   
  4. if (pi) // pi has value 0, so condition eva luates as false   
  5. // . . .   
  6. if (pi2) // pi2 points to ival, so it is not 0; the condition eva luates as true   
  7. // . . .  

Any nonzero pointer eva luates as true

Given two valid pointers of the same type, we can compare them using the equality (==) or inequality (!=) operators. The result of these operators has type bool. Two pointers are equal if they hold the same address and unequal otherwise. Two pointers hold the same address (i.e., are equal) if they are both null, if they address the same object, or if they are both pointers one past the same object. Note that it is possible for a pointer to an object and a pointer one past the end of a different object to hold the same address. Such pointers will compare equal.

Because these operations use the value of the pointer, a pointer used in a condition or in a comparsion must be a valid pointer. Using an invalid pointer as a condition or in a comparison is undefined.

§ 3.5.3 (p. 117) will cover additional pointer operations.
void* Pointers

The type void* is a special pointer type that can hold the address of any object. Like any other pointer, a void* pointer holds an address, but the type of the object at that address is unknown:

  1. double obj = 3.14, *pd = &obj;   
  2. // ok: void* can hold the address value of any data pointer type   
  3. void *pv = &obj; // obj can be an object of any type   
  4. pv = pd; // pv can hold a pointer to any type 

There are only a limited number of things we can do with a void* pointer: We can compare it to another pointer, we can pass it to or return it from a function, and we can assign it to another void* pointer. We cannot use a void* to operate on the object it addresses—we don’t know that object’s type, and the type determines what operations we can perform on the object.

Generally, we use a void* pointer to deal with memory as memory, rather than using the pointer to access the object stored in that memory. We’ll cover using void* pointers in this way in § 19.1.1 (p. 821). § 4.11.3 (p. 163) will show how we can retrieve the address stored in a void* pointer.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.3 Compound Types (5) 下一篇2.3 Compound Types (7)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·用 Python 进行数据 (2025-12-25 15:49:09)
·如何学习Python数据 (2025-12-25 15:49:07)
·利用Python进行数据 (2025-12-25 15:49:04)
·Java 学习线路图是怎 (2025-12-25 15:19:15)
·关于 Java 学习,有 (2025-12-25 15:19:12)