Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

c - Why is the output `0` in this case?

#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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...