简体   繁体   English

指针增量如何工作

[英]How pointer increment works

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 输出= 5,5

Why the value of *q is 5 it should have some garbage value? 为什么*q值为5,它应该有一些垃圾值?

int main(void) int main(无效)

{

    int n1 = 2, n2 = 5;

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

    *p = *(++q);

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

    return 0;

}

output= 2,2 输出= 2,2

And how is this happening? 怎么回事? Can anyone explain how precedence rule works in pointers? 谁能解释优先规则在指针中的工作原理?

*p = *(q++); is (more or less) equivalent to *p = *q; q++; (或多或少)等于*p = *q; q++; *p = *q; q++; , so p is fine. ,所以p很好。 q++ will be evaluated, yielding the old value of q (ie the value pre-increment). 将评估q++ ,得出q的旧值(即,值预递增)。 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. 尽管q不再指向您当时拥有的内存,但在printf调用中对q的引用确实具有未定义的行为。 A million different things could be causing that (eg 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. 一百万种不同的原因可能会导致这种情况(例如,上次分配内存,也许在那里分配了5个内存,编译器太好了,试图为您提供帮助,等等),但是您不能也不应该依赖此行为。 Doing so is dangerous, and this program would likely crash or output nonsense on many compilers/operating systems/hardware. 这样做很危险,并且该程序可能在许多编译器/操作系统/硬件上崩溃或输出废话。

Why the value of *q is 5 it should have some garbage value? 为什么* q的值为5,它应该有一些垃圾值?

It is due to the postfix incrementation in *(q++) which acts after the pointer dereference and the assignment to *p . 这是由于*(q++)后缀增加导致的,该后缀在指针取消引用和分配给*p之后起作用。

So, the current value of the address pointed by *q is assigned to *p , and then q is incremented to a "garbage value" . 因此,将*q指向的地址的当前值分配给*p然后将q递增为“垃圾值”

This strange result in printing 5,5 is undefined behaviour. 打印5,5这种奇怪结果是不确定的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM