Ari*_*ome 0 c++ error-handling pointers
我有以下代码:
#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);
}
Run Code Online (Sandbox Code Playgroud)
但是,在运行可执行文件时,输出是 2 而不是 3。我知道 *(pointer) 给出存储在指针处的值,并且 (operand)++ 增加操作数的值并将其存储在操作数本身。那么,造成这种意外结果的确切原因是什么?
使用的编译器:
g++(MinGW-W64 x86_64-posix-seh,由布莱希特桑德斯构建)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
注意:我在学习时使用这个视频,在解释的人的机器上,*a++ 工作正常。
根据运算符优先级规则,您的表达式被解释为
void Increment(int* a)
{
*(a++);
}
Run Code Online (Sandbox Code Playgroud)
即你增加一个指针,而不是它的值。您需要添加括号:
void Increment(int* a)
{
(*a)++;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |