指针增量的工作原理 [英] How pointer increment works

查看:68
本文介绍了指针增量的工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(void)
{
    int n1 = 2, n2 = 5;
    int *p = &n1, *q = &n2;
    *p = *(q++);
    printf("%d,%d", *p, *q);
    return 0;
}

输出= 5,5

为什么 *q 的值为 5 应该有一些垃圾值?

Why the value of *q is 5 it should have some garbage value?

int main(void)

int main(void)

{

    int n1 = 2, n2 = 5;

    int *p = &n1, *q = &n2;

    *p = *(++q);

    printf("%d,%d", *p, *q);

    return 0;

}

输出= 2,2

这是怎么发生的?谁能解释优先规则如何在指针中工作?

And how is this happening? Can anyone explain how precedence rule works in pointers?

推荐答案

*p = *(q++); 是(或多或少)等价于 *p = *q;q++;,所以 p 没问题.q++ 将被评估,产生 q 的旧值(即值预增量).您在那里看到的是预期的行为.

*p = *(q++); is (more or less) equivalent to *p = *q; q++;, so p is fine. q++ will be evaluated, yielding the old value of q (i.e. the value pre-increment). What you're seeing there is the expected behavior.

您确实在 printf 调用中对 q 的尊重有未定义的行为,尽管因为 q 不再指向您拥有的内存观点.一百万种不同的事情可能导致这种情况(例如,上次分配内存时,可能是 5,编译器太好了并试图帮助您等),但您不能也不应该依赖这种行为.这样做很危险,而且这个程序可能会在许多编译器/操作系统/硬件上崩溃或输出无意义的信息.

You do have undefined behavior in the deference of q in the printf call though since q no longer points at memory you own at that point. A million different things could be causing that (e.g. last time the memory was allocated, maybe a 5 was there, the compiler is being too nice and trying to help you, etc), but you cannot and should not depend on this behavior. Doing so is dangerous, and this program would likely crash or output nonsense on many compilers/operating systems/hardware.

这篇关于指针增量的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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