打印变量(或指针)的存储位置
问题描述:
我想打印一个变量的存储位置。我Google一下,我发现这一点:
I want to print where a variable is stored. I Google it and I found this:
int *p;
printf("memory location of ptr: %p\n", (void *)p);
如果我写这篇文章,是不是?
If I write this, is it right?
printf("memory location of ptr: %p\n", &p);
我编译它,我没有得到任何错误或警告,但载文,如果我把他们都在节目中的两个语句不返回相同的值。
I compiled it and I don't get any errors or warnings but theses two statements don’t return the same value if I put both of them in the program.
答
比方说你有这些声明:
int i;
int *p = &i;
这将是这个样子的记忆:
It would look something like this in memory:
+---+ +---+
| p | --> | i |
+---+ +---+
如果您再使用&安培; P
你得到一个指针 P
,让你有这样的:
If you then use &p
you get a pointer to p
, so you have this:
+----+ +---+ +---+
| &p | --> | p | --> | i |
+----+ +---+ +---+
所以 P
的值为的地址我
和的价值&安培; p
是 p
的地址。这就是为什么你会得到不同的值。
So the value of p
is the address of i
, and the value of &p
is the address of p
. That's why you get different values.