【问题标题】:Pointer not incrementing in printf statement?指针在 printf 语句中不递增?
【发布时间】:2022-01-19 22:21:57
【问题描述】:

这段代码怎么来的

#include <stdio.h>

int main(){
  int y=42;
  int *p=&y;
  (*p)++;
  printf("%d\n",*p);
  return 0;
}

按预期输出 43,但是这段代码

#include <stdio.h>

int main(){
  int y=42;
  int *p=&y;
  printf("%d\n",(*p)++);
  return 0;
}

输出 42?

【问题讨论】:

  • 你知道为什么叫post-increment吗?
  • @EugeneSh。因为 ++ 在应用运算符的表达式之后?
  • 你试过printf("%d\n", ++*p);吗?
  • @CostantinoGrana 我会说视觉表现暗示了它的运作方式,而且绝对是次要的(虽然不确定这是否是讽刺评论)。
  • @EugeneSh。我应该用一个????。我显然是在开玩笑。

标签: c pointers memory-address


【解决方案1】:

x++ 是后自增运算符。它增加它被调用的变量,但计算为 before 增量的值。

printf 语句分成两个语句可能会更清楚:

int pBeforeIncrement = (*p)++; // After this statement, pBeforeIncrement + 1 == p
printf("%d\n", pBeforeIncrement);

【讨论】:

    【解决方案2】:
      printf("%d\n",(*p)++);
    

    将值传递给打印后,它会增加值。它被称为post增量。

      printf("%d\n",++(*p));
    

    它在将值传递给打印之前增加值。它被称为pre增量。

    int main(){
      int y=42;
      int *p=&y;
      printf("(*p) = %d\n",(*p));
      printf("(*p)++ = %d\n",(*p)++);
      printf("(*p) = %d\n",(*p));
      printf("++(*p) = %d\n",++(*p));
      return 0;
    }
    

    https://godbolt.org/z/Ke5Y6e3q8

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      相关资源
      最近更新 更多