问题
#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:
- de-reference
ptr
, resulting in the value ofptr[0]
- print out the
int
step 1 evaluates to, that isptr[0]
- increment
ptr
so it points toptr[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
*ptr
- use the value of
*ptr
asprintf("%d ", *ptr);
ptr = ptr + 1
The output of such expressions can be understood by:
- Precedence of prefix ++ and
*
is same. Associativity of both is right to left.- 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