如何能一个地址有多个值? [英] How can an address have multiple values?
问题描述
int i[5]={0,1,2,3,4,};
int *ip=&i[0];
printf("%d,%d,%d,%d,%d,%d,%d,%d",*ip,ip,&ip,&i,&i[0],i,i[0],*(&i));
上面这段code的,我在我的补偿得到的输出是
The output of above piece of code that I got in my comp is
0,2358832,2358824,2358832,2358832,2358832,0,2358832
注意这两个 IP =&安培; I = 2358832
但 * IP = 0
和 *(&安培; I)= 2358832
。
怎么能地址,在这种情况下2358832,有两个值?
Observe that both ip=&i=2358832
but *ip=0
and *(&i)=2358832
.
How can one address, in this case 2358832, have two values?
推荐答案
我会试着用图表帮助解释了。
I'll try to explain with help of diagram.
int i[5]={0,1,2,3,4,};
int *ip=&i[0];
这code后,我们有两个变量:数组 I
5 INT
和指针 IP
指向数组的第一个元素 I
(即包含数组的第一个元素的地址我
)。让我们来看看这些变量是如何在内存布局(这张图我假设整数有大小4和指针有大小8,你的系统上也可以是不同的,但是对于你的问题,现在并不重要):
After this code we have two variables: array i
of 5 int
s and pointer ip
which points to first element of array i
(i.e. contains the address of first element of array i
). Let's see how these variables are laid out in memory (for this diagram I assume that ints have size 4 and pointers have size 8, on your system it can be different, but for your question it doesn't matter now):
现在让我们来看看printf的参数,并用图表解释它们:
Now let's have a look at printf arguments and explain them using diagram:
-
* IP
- 把变量的值IP
- 2358832 - 和除preting这个值作为地址,获得类型的值INT
(因为IP
已键入为int *它存储在该地址
) - 0 -
IP
- 获取变量的值IP
- 2358832 -
&放大器; IP
- 获取地址变量IP
- 2358824 -
&放大器;我
- 获取变量I
的地址 - 2358832 -
- 的注1:的变量通常占用超过一个存储单元,在这种情况下变量的地址是指通过该变量占用的第一个存储单元的地址=>变量
我
占用大量细胞,但有地址为2358832 - 它的第一个单元格的地址;
*ip
- "Take the value of variableip
- 2358832 - and, interpreting this value as address, get the value of typeint
(becauseip
has typeint *
) which is stored at this address - 0";ip
- "Get the value of variableip
- 2358832";&ip
- "Get the address of variableip
- 2358824";&i
- "Get the address of variablei
- 2358832";- Note 1: variable usually occupies more than one memory cell, in such case "address of variable" means address of first memory cell which is occupied by this variable => variable
i
occupy many cells but have address "2358832" - address of its first cell;
- 的注2:的变量
IP
占据多个单元格太(8我们的图上)
- Note 2: variable
ip
occupies more than one cell too (8 on our diagram)
-
&放大器;我
=> 2358832 (见上文)。请注意,此中间值(作为任何其他值!)已键入。在这种情况下,类型为INT(*)[5]
- 指针数组的
&i
=> 2358832 (see above). Note that this intermediate value (as any other value!) has type. In this case type isint (*)[5]
- pointer to array.
-
*(&安培; I)
- 把它存储在地址 2358832 阵列的价值。正如我们已经知道,阵列的价值是指这个数组的第一个元素的地址 - 2358832
*(&i)
- "Get the value of array which is stored at address 2358832". As we already know, "value of array" means the address of first element of this array - 2358832.
这篇关于如何能一个地址有多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Note 1: variable usually occupies more than one memory cell, in such case "address of variable" means address of first memory cell which is occupied by this variable => variable
- 的注1:的变量通常占用超过一个存储单元,在这种情况下变量的地址是指通过该变量占用的第一个存储单元的地址=>变量