首页 > 解决方案 > 为什么在 cpp/c 中使用指针引用时自增运算符 (++) 不起作用

问题描述

我正在编写与 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++14increment

解决方案


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

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


推荐阅读