我是 C 语言新手
不明白这里发生了什么
struct person {
int age;
};
main ()
{
struct person p , *ptr;
ptr = &p;
printf ("%d \n" , ++ptr->age );
printf("%d" , ptr++->age);
return 0;
}
How Both printf statements prints 1 ?
最佳答案
这个表达式
++ptr->count;
相当于
++( ptr->count );
因此它增加了ptr
指向的结构的数据成员count
。
++ptr->count
中的 operator ->
是后缀运算符,其优先级高于任何一元运算符(包括预自增运算符 ++)
.
在这个表达式中
ptr++->count;
有两个后缀运算符:后置自增运算符++
和运算符->
。它们是从左到右评估的。后自增运算符++的值是其操作数自增前的值。因此,该表达式返回 ptr
所指向的结构的数据成员 count
在递增之前的值。指针本身递增。
根据 C 标准(6.5.2.4 后缀递增和递减运算符)
2 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)....
关于c - 结构指针上的前/后增量运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31626016/