问题描述
我有一个关于增加指针的问题,我不太明白。
I have a question about incrementing in pointers that I dont quite understand.
我们看到两个小程序:
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
In this first program I increment what pPointer is pointing to like this "*pPointer = *pPointer +1".And as I expected iTuna changed to "2" and the program printed out the value "2"
int iTuna=1;
int* pPointer= &iTuna;
*pPointer++; //Increment what pPointer is pointing to.
cout << iTuna << endl;
system("PAUSE");
return 0;
$ b $ p
这里我递增ppointer指向的是* pPointer ++。但这里iTuna保持为1,程序打印出值1。
虽然我期望这个工作作为第一个,它没有。
Here I incremented incremented what pPointer is pointing to this was "*pPointer++". But here iTuna stays as "1" and the programs prints out the value "1" . Although I expected this one to work as the first, it didn't.
请帮助我,告诉我为什么第二个代码不是
Please Help me and tell me why the second peice of code isn't working like I expected and how to get around it.
谢谢
推荐答案
*pPointer++;
相当于
*pPointer;
pPointer++;
所以它递增指针,而不是解除引用的值。
so it increments the pointer, not the dereferenced value.
您可能会不时在字符串复制实现中看到这种情况,例如
You may see this from time to time in string copy implementations like
while(*source)
*target++ = *source++;
由于你的问题是运算符优先级的问题,如果你想deref指针, ,可以使用括号:
Since your problem is a matter of operator precedence, if you want to deref the pointer, and then increment, you can use parens:
(*pointer)++;
这篇关于递增指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!