我试图通过自己澄清指针指向的地址,指针本身的地址和地址所指的值来更好地理解简单指针。所以我写了一小段代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int *p;
int **pp;
a = 42;
/* Take the address of a */
p = &a;
/* Take the address of p */
pp = &p;
printf("Address of int &a: %p\n\n", &a);
printf("value of a: %d\n\n", a);
printf("Address where *p points to via (void *)p: %p\n\n", (void *)p);
printf("Value that *p points to via *p: %d\n\n", *p);
printf("Address of *p itself via (void *)&p: %p\n\n", (void *)&p);
printf("Address where **p points to via (void *)pp: %p\n\n", (void *)pp);
printf("Value that **pp points to via **pp: %d\n\n", **pp);
printf("Address of **p itself via (void *)&pp: %p\n\n", (void *)&pp);
return EXIT_SUCCESS;
}
这一切都按预期工作(如果我在这里犯了任何错误,请纠正我。)现在,我想更深入一级,并使用指向指针***ppp
的指针,并为指针pp
指向指向地址*p
指向的地址。这是a
的地址。以下是我认为我能做到的事情:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int *p;
int **pp;
int **ppp;
a = 42;
/* Take the address of a */
p = &a;
/* Take the address of p */
pp = &p;
ppp = &pp;
printf("Address of int &a: %p\n\n", &a);
printf("value of a: %d\n\n", a);
printf("Address where *p points to via (void *)p: %p\n\n", (void *)p);
printf("Value that *p points to via *p: %d\n\n", *p);
printf("Address of *p itself via (void *)&p: %p\n\n", (void *)&p);
printf("Address where **pp points to via (void *)pp: %p\n\n", (void *)pp);
printf("Value that **pp points to via **pp: %d\n\n", **pp);
printf("Address of **pp itself via (void *)&pp: %p\n\n", (void *)&pp);
printf("Address where ***ppp points to via (void *)ppp: %p\n\n", (void *)ppp);
printf("Value that ***ppp points to via ***ppp: %d\n\n", ***ppp);
printf("Address where ***ppp points to via (void *)&ppp: %p\n\n", (void *)&ppp);
return EXIT_SUCCESS;
}
但是这给了我一个不兼容的指针警告。有人可以向我解释为什么这不起作用以及对printf()
的呼叫是否正确?
答案 0 :(得分:3)
错误就在这一行 int ** ppp; / *它应该是*** ppp,因为你指向指向另一个的指针* /
答案 1 :(得分:2)
问题在于:
int **ppp;
那应该是
int ***ppp;
现在你正试图强制一个三指针,成为一个双指针。这可能会在这一行上给你一个错误:
ppp = &pp;
您可能希望查看this article的第2位:)。
<强> P.S。强> 如果您提供行号和特定错误,以备将来参考。人们可能想要更好,更好地帮助你:)