为什么对于指针 *P,P [0]是存储在P和P [1]的地址是P本身的地址?

发布于 2025-01-22 11:40:02 字数 317 浏览 4 评论 0原文

代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

春花秋月 2025-01-29 11:40:02

该声明

printf("%x\n %d\n %x\n", p, p[0], p[1]);

通过两个原因调用了不确定的行为。

第一个是要输出指针,您应该使用正确的转换说明符。第二个是您不得取消指向没有指向有效对象的p [1]的指针。

相反,您可以写作

printf("%p\n %d\n %p\n", ( void * )p, p[0], ( void * )( p + 1 ) );

This statement

printf("%x\n %d\n %x\n", p, p[0], p[1]);

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

printf("%p\n %d\n %p\n", ( void * )p, p[0], ( void * )( p + 1 ) );
夜雨飘雪 2025-01-29 11:40:02

当您在代码中评估p [1]时,您正在调用未定义的行为,以便您的程序可以执行任何操作。

这是不确定的行为,因为pn只是一个整数,而不是整数数组。因此,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 at n which is just a single integer, not an array of integers. So p[0] is n, but p[1] is undefined. Basically this is an array overflow bug.

溇涏 2025-01-29 11:40:02

您的程序具有不确定的行为,因为它会导致指向任何指向任何内容的指针。

您经历的特定症状与阅读功能中的下一个变量一致

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

凉薄对峙 2025-01-29 11:40:02

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文