Why is the output `0` in this case?

喜欢而已 提交于 2020-08-20 14:22:49

问题


#include <stdio.h>

int main(void)
{
    int i;
    int *p = (int *) malloc(5 * sizeof(int));

    for (i=0; i<10; i++)
        *(p + i) = i;

    printf("%d ", *p++);
    return 0;
}

So, I ran this code. Now I was told here that Why won't the output be 4 in this case? (in accepted answer) that *p++ will increment pointer first and then dereference it. Therefore, in the above code, shouldn't the pointer be incremented first and then de-referenced and hence output should be 1? Instead, output comes out to be 0. Why?


回答1:


You got the precedence part right, but let's see about the postfix increment operator property, shall we?

C11 standard says in chapter §6.5.2.4, Postfix increment and decrement operators

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [...]

So, the variable itself will experience the effect of the increment, but the statement, in which the variable is present(with the postfix increment) will avail the existing value of the variable, not the incremented value. The increment, will be executed as a side-effect at a later part.




回答2:


This statement

printf("%d ", *ptr++);

does the following:

  1. de-reference ptr, resulting in the value of ptr[0]
  2. print out the int step 1 evaluates to, that is ptr[0]
  3. increment ptr so it points to ptr[1]

To print out ptr[1] use:

printf("%d ", *++ptr);



回答3:


Please note that it is post increment. Thus, the returned value of the postfix ++ operator is the value of the operand itself, then as a side effect, the value of the operand object is incremented.

The expression *ptr++ will be

  1. *ptr
  2. use the value of *ptr as printf("%d ", *ptr);
  3. ptr = ptr + 1

The output of such expressions can be understood by:

  1. Precedence of prefix ++ and * is same. Associativity of both is right to left.
  2. Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.

Therefore, in the above code, shouldn't the pointer be incremented first and then de-referenced and hence output should be 1?

Use for this requirement the following:

printf("%d ", *++ptr);



回答4:


Firstly, you should add #include <stdlib.h>. Secondly, you should correct your code int *p = (int *) malloc(10 * sizeof(int));. Then the *p++ stands for 1. printf *p; 2. p++. If you want to get value 1, you should use the code printf("%d ", *++p);. I hope this can help you.



来源:https://stackoverflow.com/questions/31672874/why-is-the-output-0-in-this-case

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