How pointer increment works

拜拜、爱过 提交于 2021-02-08 10:16:49

问题


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

output= 5,5

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

int main(void)

{

    int n1 = 2, n2 = 5;

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

    *p = *(++q);

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

    return 0;

}

output= 2,2

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


回答1:


*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.

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.




回答2:


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

It is due to the postfix incrementation in *(q++) which acts after the pointer dereference and the assignment to *p.

So, the current value of the address pointed by *q is assigned to *p, and then q is incremented to a "garbage value".

This strange result in printing 5,5 is undefined behaviour.



来源:https://stackoverflow.com/questions/32427913/how-pointer-increment-works

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!