了解指向指针的指针
我有以下代码:
#include <stdio.h>
int main(void)
{
int a[10]={10,20,30,40,50,60,70,80,90,100};
int *p;
p=a;
int **d=&p;
printf("Address stored in p:%d\n",p);
printf("Pointer p's address:%d\n",d);
printf("Pointer d's content:%d\n",*d);
printf("Pointed array content:%d\n",(*d)[9]);
printf("Unexpected:\n");
for (int i = 0; i < 10; ++i)
{
printf("%d\n",d[i]);
}
printf("Expected:\n");
for (int i = 0; i < 10; ++i)
{
printf("%d\n",(*d)[i]);
}
}
我意识到,第一个循环是将指针指向指针的错误方法。尽管我得到以下输出,但执行后:
6487520
10
30
50
70
90
2
6487512
1
7607184
第一个迭代显示[0]的地址,但是为什么我会用奇数索引获得数组的内容?这种行为是随机的(取决于编译器),并且在理解它时毫无意义?
I have the following code:
#include <stdio.h>
int main(void)
{
int a[10]={10,20,30,40,50,60,70,80,90,100};
int *p;
p=a;
int **d=&p;
printf("Address stored in p:%d\n",p);
printf("Pointer p's address:%d\n",d);
printf("Pointer d's content:%d\n",*d);
printf("Pointed array content:%d\n",(*d)[9]);
printf("Unexpected:\n");
for (int i = 0; i < 10; ++i)
{
printf("%d\n",d[i]);
}
printf("Expected:\n");
for (int i = 0; i < 10; ++i)
{
printf("%d\n",(*d)[i]);
}
}
I realize that the first loop is an incorrect way to dereference a pointer to pointer. Upon execution though I get the following output:
6487520
10
30
50
70
90
2
6487512
1
7607184
The first iteration shows a[0]'s address but why am I getting the array's content with odd indexes? Is this behavior random(depending on compiler) and pointless in understanding it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们无法知道为什么会产生这些数字。一般的答案是,从未知指针中读取值是不确定的行为。我们无法知道它可能会返回的内容,即使返回的值在程序的运行之间都保持一致。该程序甚至可能崩溃或产生怪异的行为。
不过,更实用的答案是,我们知道
d
在堆栈上,因此我们观察到的值也可能是堆栈的一部分。d
是一个指针而不是整数,因此它的尺寸可能不同。由于我们看到了每个第二个值,因此您的指针可能是系统上int
的大小的两倍。您可以通过添加类似的内容来测试该理论:
当我在系统上运行它时,我会得到:
We have no way of knowing why it produced those numbers. The general answer is that reading a value from an unknown pointer is undefined behavior. We have no way of knowing what it might return or even if the value returned will be consistent between runs of the program. The program may even crash or produce weird behavior.
The more practical answer though is that we know that
d
is on the stack so the values we observe are likely also part of the stack.d
is a pointer not an integer so it may have a different size. Since we see every second value, it likely means your pointer is twice as large as the size of anint
on your system.You can test this theory by adding something like this:
When I run it on my system I get: