Incrementing Pointers

Viewed 43728

I have a question about incrementing in pointers that I dont quite understand.

Lets see 2 small programs:

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

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;

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.

Thank You

6 Answers

In the first case, the content of the pointer is incremented because *pPointer correspond to the content of the variable iTuna.

In the second one, the content is not incremented because you pPointer incrementing the pointer address. Remembering operator precedence rules, postfix operators such as increment (++) and decrement (--), have higher precedence than prefix operators, such as the dereference operator (*). Therefore, writting

*pPointer++

is equivalent to

*(pPointer++)

And what it does is to increase the value of pPoiner (so it now points to the next element), but because ++ is used as postfix, the whole expression is evaluated as the value pointed originally by the pointer (the address it pointed to before being incremented).

The correct code to have what you are expecting for is the following:

++*pPointer

or

(*pPointer)++

Related