【问题标题】:Why does increment operator (++) not work when you reference using pointers in cpp/c [duplicate]为什么在 cpp/c 中使用指针引用时自增运算符 (++) 不起作用 [重复]
【发布时间】:2020-10-01 05:33:44
【问题描述】:

我正在编写与 C/C++ 中的引用相关的代码。我做了一个指针并将它放入一个递增它的函数中。在函数中,我写了*ptr++ 并尝试增加指针指向的整数的值。

#include <iostream>
using namespace std;

void increment(int *ptr)
{
    int &ref = *ptr;
    *ptr++; // gets ignored?
    ref++;
}

int main()
{
    int a = 5;
    increment(&a);
    cout << a;

    return 0;
}

谁能告诉我为什么我不能增加变量?我尝试使用+=1 增加它,它可以工作,但不能使用++ 运算符?

【问题讨论】:

标签: c++ c++14 increment


【解决方案1】:

++ 的优先级高于*,因此*ptr++ 被视为*(ptr++)。这会增加指针,而不是它指向的数字。

要增加数字,请使用(*ptr)++

【讨论】:

    【解决方案2】:

    你的代码是:

    *ptr++;
    

    相当于:

    *(ptr++);
    

    这意味着指针先递增然后取消引用。发生这种情况是因为递增运算符 ++ 的优先级高于取消引用运算符 * 。所以你应该使用:

    (*ptr)++;
    

    这里第一个指针被取消引用然后递增。

    【讨论】:

      猜你喜欢
      • 2017-02-08
      • 1970-01-01
      • 2015-07-06
      • 2018-12-03
      • 2017-03-16
      • 1970-01-01
      • 2021-05-22
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多