gpt4 book ai didi

c++ - 递增指针

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:31 26 4
gpt4 key购买 nike

我有一个关于指针递增的问题,我不太明白。

让我们看两个小程序:

int iTuna=1;
int* pPointer= &iTuna;
*pPointer = *pPointer + 1 ; //Increment what pPointer is pointing to.
cout << iTuna << endl;

在第一个程序中,我增加了 pPointer 指向的内容,如“*pPointer = *pPointer +1”。正如我所料 iTuna 更改为“2”并且程序打印出值“2”

int iTuna=1;
int* pPointer= &iTuna;
*pPointer++; //Increment what pPointer is pointing to.
cout << iTuna << endl;
system("PAUSE");
return 0;

这里我递增递增 pPointer 指向的是“*pPointer++”。但这里 iTuna 保持为 "1"并且程序打印出值 "1"。 虽然我希望这个能像第一个一样工作,但事实并非如此。

请帮助我并告诉我为什么第二段代码没有像我预期的那样工作以及如何解决它。

谢谢

最佳答案

*pPointer++;

相当于

*pPointer;
pPointer++;

所以它增加了指针,而不是取消引用的值。

您可能会不时在字符串复制实现中看到这一点,例如

  while(*source)
*target++ = *source++;

由于您的问题是运算符优先级的问题,如果您想取消引用指针,然后递增,您可以使用括号:

(*pointer)++;

关于c++ - 递增指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11754419/

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