Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing Pointers

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

like image 272
Mohamed Ahmed Nabil Avatar asked Aug 01 '12 07:08

Mohamed Ahmed Nabil


3 Answers

*pPointer++;

is equivalent to

*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++;

Since your problem is a matter of operator precedence, if you want to deref the pointer, and then increment, you can use parens:

(*pointer)++;
like image 162
Michael Chinen Avatar answered Oct 10 '22 19:10

Michael Chinen


++ operator precedence is higher than *d dereference.

What you write is actually

*(p++)

However you should use

(*p)++
like image 34
SwiftMango Avatar answered Oct 10 '22 18:10

SwiftMango


 *ptr++; - increment pointer and dereference old pointer value

It's equivalent to:

*(ptr_p++) - increment pointer and dereference old pointer value

Here is how increment the value

(*ptr)++; - increment value

That's becuase ++ has greater precedence than *, but you can control the precedence using ()

like image 3
Andrew Avatar answered Oct 10 '22 18:10

Andrew