c - 结构指针上的前/后增量运算符

标签 c pointers operator-precedence post-increment pre-increment

我是 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/

相关文章:

c++ - 似乎无法获得一个 char 数组来离开函数并在 main 中可用

MySQL AND条件括号不起作用

c - 无法从函数返回字符串

c - 如何正确计算结构的大小?

C 数据结构 - 存储二叉树的表示

Python 优先级

javascript - OOP 语言中的变量重新分配

c - 警告 : C4013 in C lang

c - 我的这个推理哪里错了?

pointers - Go Pointers - 通过指针将值附加到 slice