gpt4 book ai didi

C++使用指针简单自减(疑惑)

转载 作者:太空狗 更新时间:2023-10-29 19:37:59 26 4
gpt4 key购买 nike

我对这种行为有些疑惑。谁能解释一下

  void Decrement(int* x){
*x--; //using this line, the output is 5

//*x=*x-1; //using this l ine, the output is 4

}

int main(){
int myInt=5;
Decrement(&myInt);
cout<<myInt<<endl;
return 0;
}

Output: 5

最佳答案

*x-- 表示*(x--)。也就是说,您的程序修改的是 x,而不是它指向的内容。因为它是按值传递的,所以该修改对 main() 没有影响。要匹配您的注释行,您需要使用 (*x)--

关于C++使用指针简单自减(疑惑),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14516365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com