C:为什么指针和& pointer具有不同的值? [英] C: Why do pointer and &pointer have different values?

查看:104
本文介绍了C:为什么指针和& pointer具有不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在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;

第二,您对&nprintf指定符有误.您需要%p:

Second, you have the wrong printf specifier for &n. You need %p:

printf("n: %i, &n: %p\n", n, &n);

这篇关于C:为什么指针和& pointer具有不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆