为什么对于指针 *P,P [0]是存储在P和P [1]的地址是P本身的地址?
代码
int n = 25;
int *p = &n;
printf("%x\n %d\n %x\n", p, p[0], p[1]);
返回:
\<adress-of-p
25
\<adress-of-p>
当然我永远不会这样做,但是在K&amp; r中指出
“如果pa是指指针,则表达式可以与下标一起使用; pa [i]与 *(pa+i)相同。
所以我很好奇。
The code
int n = 25;
int *p = &n;
printf("%x\n %d\n %x\n", p, p[0], p[1]);
returns:
\<adress-of-p
25
\<adress-of-p>
Of course I would never do this but in K&R states that
"if pa is a pointer, expressions may use it with a subscript; pa[i] is identical to *(pa+i).
so I was curious.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该声明
通过两个原因调用了不确定的行为。
第一个是要输出指针,您应该使用正确的转换说明符。第二个是您不得取消指向没有指向有效对象的
p [1]
的指针。相反,您可以写作
This statement
invokes undefined behavior by two reasons.
The first one is that to output a pointer you should use a correct conversion specifier. The second one is that you may not dereference a pointer like this
p[1]
that does not point to a valid object.Instead you could write for example
当您在代码中评估
p [1]
时,您正在调用未定义的行为,以便您的程序可以执行任何操作。这是不确定的行为,因为
p
点n
只是一个整数,而不是整数数组。因此,p [0]
是n
,但是p [1]
是未定义的。基本上,这是一个数组溢出错误。When you evaluate
p[1]
in your code, you are invoking undefined behavior so your program can do anything.It is undefined behavior because
p
points atn
which is just a single integer, not an array of integers. Sop[0]
isn
, butp[1]
is undefined. Basically this is an array overflow bug.您的程序具有不确定的行为,因为它会导致指向任何指向任何内容的指针。
您经历的特定症状与阅读功能中的下一个变量一致
Your program has undefined behaviour, because it dereferences a pointer that doesn't point to anything.
The particular symptoms you have experienced are consistent with reading the next variable in the function
p [n]语法是 *(p + n)的语法糖。
因此,p [0]为 *(p + 0),是 *p,并且由于p指向n, *p是n的值,即25。
现在,p [1]为 *(p + 1) 。因此,从理论上讲,您将获得的是n后记忆中的下一个整数。在这种特殊情况下,内存中的下一件事恰好是P本身,即n的地址。 (请注意,这是不能保证的,您的编译器只是选择以这种方式安排东西。)
The p[n] syntax is syntactic sugar for *(p + n).
So p[0] is *(p + 0), which is *p, and since p points to n, *p is the value of n, which is 25.
Now, p[1] is *(p + 1). So in theory what you would get is the next integer in memory following n. In this particular case, the next thing in memory happened to be p itself, which is the address of n. (Note that this isn't guaranteed, your compiler just chose to arrange things that way.)