【问题标题】:printf treats *p++ differently from what happens to p [duplicate]printf 对待 *p++ 的方式与对待 p 的方式不同 [重复]
【发布时间】:2019-09-24 23:14:17
【问题描述】:

*p++ 通常将 1 添加到指针然后引用。 但是 printf 只是在取消引用之后取值,而指针增加然后取消引用。

#include<stdio.h>

int main()
{
    int a[] = { 10,20,30 };
    int *p = a;

    printf("%d\n", *p++);//this makes p point at 20 but prints 10
    printf("%d\n", *p);//prints 20
    printf("%d\n", a[0]);//prints 10

}

有人能解释一下为什么会这样吗?

提前致谢

【问题讨论】:

标签: c++ c pointers printf


【解决方案1】:

*p++ 通常给指针加 1 然后 [de]references

No it doesn't.

您使用了后缀增量(++p 之后),因此提供的是原始值,而不是新增加的值。

你在想*++p

【讨论】:

  • 我知道您在个人资料中声明“不要在 cmets 中写答案。” - 因此我立即投赞成票... ;-)
  • @Scheff 因此我没有支持您在 cmets 中的回答 ;)
猜你喜欢
  • 2014-07-02
  • 1970-01-01
  • 1970-01-01
  • 2022-10-19
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多