【问题标题】:Why does the post increment operator not increment the actual value of stored at an integer pointer? [closed]为什么后自增运算符不增加存储在整数指针处的实际值? [关闭]
【发布时间】:2021-06-03 02:41:57
【问题描述】:

我有以下代码:

#include<iostream>
#define LOG(x) std::cout << x << std::endl;
void Increment(int* a)
{
    *a++;
}
int main()
{
    int a = 8;
    int& ref = a;
    ref = 2;
    Increment(&a);
    LOG(a);
}

但是,在运行可执行文件时,输出是 2 而不是 3。我知道 *(pointer) 给出存储在指针处的值,而 (operand)++ 递增操作数的值并将其存储在内存中操作数本身的地址。那么,造成这种意外结果的确切原因是什么?

使用的编译器

g++(MinGW-W64 x86_64-posix-seh,由 Brecht Sanders 构建)10.2.0

版权 (C) 2020 Free Software Foundation, Inc.

这是免费软件;查看复制条件的来源。没有

保修;甚至不是为了适销性或特定用途的适用性。

================================================ ============================================

使用的构建命令

D:\mingw64\mingw64\bin\g++.exe -g D:\programming\cpp\cherno\references\Main.cpp -o D:\programming\cpp\cherno\references\Main.exe

注意:我在学习时使用this 视频,在解释的人的机器上,*a++ 工作正常。

【问题讨论】:

  • 应该是(*a)++
  • *a++ 等价于*(a++)。您寻求的行为是(*a)++
  • @Peter 谢谢,但我现在不明白这个优先级问题是仅在 gcc 编译器中还是在 msvc 中?因为 youtube 视频中的那个人做了 *a++ 并且对他有用?我需要阅读编译器规范或其他东西来解决这个问题吗?
  • 你误解了那个视频。从 5:30 开始,他非常清楚如何编写正确的代码。编译器没有问题...
  • @Blastfurnace 你拯救了我的一天。万分感谢!我没明白他在 5:30 之后转到了另一个话题。

标签: c++ pointers error-handling


【解决方案1】:

你的函数“INcrement”实际上没有做任何事情,它只是让域指针“a”增加,当变量“a”离开作用域时它会被破坏。如果你想让它自己增加,按照上面答主说的去做

【讨论】:

    【解决方案2】:

    根据operator precedence的规则,你的表达式被解释为

    void Increment(int* a)
    {
        *(a++);
    }
    

    即你增加一个指针,而不是它的值。您需要添加括号:

    void Increment(int* a)
    {
        (*a)++;
    }
    

    【讨论】:

    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 2021-09-26
    • 2016-02-28
    • 1970-01-01
    • 2018-12-03
    • 2015-10-21
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多