Pointers on C——6 Pointers.3

来源:互联网 发布:腾讯视频自制网络剧 编辑:程序博客网 时间:2024/06/05 19:34

6.3 Contents of a Pointer Variable

Getting back to pointers, letʹs look at the declarations for the variables d and e. They are both declared as pointers, and they are initialized with the addresses of other variables. The initialization is done with the & operator, which produces the memory address of its operand (see Chapter 5).

让我们把话题返回到指针,看看变量d 和e 的声明。它们都被声明为指针,并用其他变量的地址予以初始化。指针的初始化是用&操作符完成的,它用于产生操作数的内存地址(见第5 章)。



The contents of d and e are addresses rather than integers or floating‐point numbers.Indeed, it is easy to see from the diagram that the contents of d match the address at which a is stored and the contents of e match the address where c is stored, as we would expect from the initialization. It is important to distinguish between the address of the variable d (112) and its contents (100), and to realize at the same time that this number 100 identifies (is the address of) some other location. At this point the house/street address analogy fails, because the contents of a house are never the address of another house.

d 和E 的内容是地址而不是整型或浮点型数值。事实上,从图中可以容易地看出, d 的内容与a的存储地址一致,而e 的内容与c 的存储地址一致,这也正是我们对这两个指针进行初始化时所期望的结果。区分变量d 的地址(112)和它的内容(100)是非常重要的,同时也必须意识到100这个数值

用于标识其他位置(是...的地址)。在这一点上,房屋/街道这个比喻不再有效,因为房子的内容绝不可能是其他房子的地址。


Before moving to the next step, letʹs look at some expressions involving these variables. Consider these declarations once more.

在我们转到下一步之前,先看一些涉及这些变量的表达式。请仔细考虑这些声明


int a = 112, b = -1;

float c = 3.14;

int *d = &a;

float *e = &c;


What is the value of each of these expressions?

下面这些表达式的值分别是什么呢?


a

b

c

d

e


The first three are easy: the value of a is 112, the value of b is ‐1 and the value of c is 3.14 , The pointer variables are just as easy. The value of d is 100, and the value of e is 108. If you said 112 and 3.14 for d and e, then youʹve made a very common mistake.The fact that d and e are declared as pointers does not change how these expressions are evaluated: the value of a variable is the number stored in the memory location assigned to the variable. It is a mistake to think that you automatically go to the locations 100 and 108 and get the values there simply because d and e are pointers. The value of a variable is the number stored in the memory location assigned to the variable, even for pointer variables.

前3 个非常容易: a 的值是112 , b 的值是-1, c 的值是3.14 。指针变量其实也很容易, d 的值是100, e 的值是108 。如果你认为d 和e 的值分别是112 和3 .l 4 ,那么你就犯了一个极为常见的错误。d 和c 被声明为指针并不会改变这些表达式的求值方式:一个变量的值就是分配给这个变量的内存位置所存储的数值。如果你简单地认为由于d 和e 是指针,所以它们可以自动获得存储于位置100和108 的值,那么你就错了。变量的值就是分配给该变量的内存位置所存储的数值,即使是指针变量也不例外。


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


原创粉丝点击