C:为什么指针和& pointer具有不同的值? [英] C: Why do pointer and &pointer have different values?
问题描述
如果我在OS X上运行以下命令:
If I run the following on OS X:
int main (void)
{
int* n; // initialise(declare) pointer
*n = 20; // the value in address pointed to by n is 20
printf("n: %i, n&: %i\n", n, &n);
return 0;
}
我得到:
n:1592302 512 ,n& ;: 1592302 480
n: 1592302512, n&: 1592302480
为什么会有不同的值?
推荐答案
为什么
pointer
和&pointer
具有不同的值?
Why do
pointer
and&pointer
have different values?
表达式&n
产生n
本身的地址,而n
求值为指针的 value ,即它指向的对象的地址.
The expression &n
yields the address of n
itself, while n
evaluates to the value of the pointer, i.e. the address of the thing it points to.
但是请注意,您具有未定义的行为首先,因为要取消引用未初始化的指针.您需要将n
指向可以写入的位置.
But note that you have undefined behaviour First of all, because you are de-referencing an uninitialized pointer. You need to make n
point somewhere you can write to.
例如,
int* n;
int i = 42;
n = &i;
// now you can de-reference n
*n = 20;
第二,您对&n
的printf
指定符有误.您需要%p
:
Second, you have the wrong printf
specifier for &n
. You need %p
:
printf("n: %i, &n: %p\n", n, &n);
这篇关于C:为什么指针和& pointer具有不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!