Pointers on C——6 Pointers.9

来源:互联网 发布:剑侠情缘手游数据互通 编辑:程序博客网 时间:2024/06/16 05:42

​6.9 Pointer Constants

Letʹs examine another expression. Assuming that the variable a is stored at location 100, what does this statement do?

让我们来分析另外一个表达式。假定变量a 存储于位置100 ,下面这条语旬的作用是什么?


*100 = 25;


It looks like the statement assigns 25 to a, because a is the variable at location 100. But not so! The statement is actually invalid because die literal 100 is of type integer, and indirection can only be performed on expressions of type pointer. If you really want to store 25 in location 100, you must use a cast.

它看上去像是把25 赋值给a ,因为a 是位置100 所存储的变量。但是,这是错的!这条语句实际上是非法的,因为字面值100 的类型是整型,而间接访问操作只能作用于指针类型表达式。如果你确实想把25 存储于位置100 ,你必须使用强制类型转换。


*(int *)100 = 25;


The cast converts the value 100 from an ʺintegerʺ to a ʺpointer to an integer.ʺ It is legal to apply indirection to this expression, so if a is stored in location 100, this statement stores the value 25 in a. However, you will need this technique rarely, if ever! Why? As mentioned earlier, you usually cannot predict where in memory the compiler will choose to put any specific variable, so you donʹt know its address ahead of time. It is easy to obtain the address of a variable with the & operator but the expression wonʹt be evaluated until the program executes, so it is too late to copy the answer into the source code as a literal constant.

强制类型转换把值100 从"整型"转换为"指向整型的指针",这样对它进行间接访问就是合法的。如果a 存储于位置100 ,那么这条语句就把值25 存储于a。但是,你需要使用这种技巧的机会是绝无仅有的!为什么?我前面提到过,你通常无法预测编译器会把某个特定的变量放在内存中的什么位置,所以你无法预先知道它的地址。用&操作符得到变量的地址是很容易的,但表达式在程序执行时才会进行求值,此时已经来不及把它的结果作用字面值常量复制到源代码。


A The only reason this example is useful is for the few times when you need to access a specific location in memory by its address, which is never done to access a variable but rather to access the hardware itself. For example, an operating system needs to communicate with the input and output device controllers to start I/O operations and to obtain results of prior operations. On some machines, communication with device controllers is accomplished by reading and writing values at specific memory addresses. Instead of accessing memory, however, these operations access the device controller interface. These locations, then, must be accessed via their addresses, which are known in advance.

这个技巧唯一有用之处是你偶尔需要通过地址访问内存中某个特定的位置,它并不是用于访问某个变量,而是访问硬件本身。例如,操作系统需要与输入输出设备控制器通信,启动1/0 操作并从前面的操作中获得结果。在有些机器上,与设备控制器的通信是通过在某个特定内存地址读取和写入值来实现的。但是,与其说这些操作访问的是内存,还不如说它们访问的是设备控制器接口。这样,这些位置必须通过它们的地址来访问,此时这些地址是预先已知的。


Chapter 3 mentioned that there is no built‐in notation for writing pointer constants. In the rare instances when they are required, they are generally written as integer literals and converted to the proper type with a cast.

第3 章曾提到并没有→种内建的记法用于书写指针常量。在那些极其罕见的需要使用它们的时候,它们通常写成整型字面值的形式,并通过强制类型转换转换成适当的类型1 。

上一章 Pointers on C——6 Pointers.8

原创粉丝点击