【问题标题】:Pre / Post increment operator on structure pointer [closed]结构指针上的前/后增量运算符[关闭]
【发布时间】:2015-10-16 00:58:09
【问题描述】:

我是 C 新手
不明白这里发生了什么

struct person {
    int age;
};

main ()
{
    struct person p , *ptr;
    ptr = &p;

  printf ("%d \n" , ++ptr->age );
  printf("%d" , ptr++->age);

  return 0;
}

两个 printf 语句如何打印 1 ?

【问题讨论】:

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


    【解决方案1】:

    这个表达式

    ++ptr->count;
    

    等价于

    ++( ptr->count );
    

    所以它增加了ptr指向的结构的数据成员count

    表达式++ptr->count 中的运算符-> 是一个后缀运算符,其优先级高于任何一元运算符,包括预增量运算符++

    在这个表达式中

    ptr++->count;
    

    有两个后缀运算符:后自增运算符++ 和运算符->。从左到右评估它们。后自增运算符 ++ 的值是其操作数在自增前的值。因此,此表达式返回 ptr 指向的结构的数据成员 count 在其递增之前的值。指针本身是递增的。

    根据 C 标准(6.5.2.4 后缀递增和递减运算符)

    2 后缀 ++ 运算符的结果是操作数的值。 作为副作用,操作数对象的值递增(即 即,将相应类型的值 1 添加到其中)....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-21
      • 2015-08-20
      • 2018-01-18
      • 1970-01-01
      • 2023-03-17
      • 2012-06-11
      • 2018-05-20
      • 1970-01-01
      相关资源
      最近更新 更多