Reputation: 187
I am trying to increment the value of an element inside an array, using a pointer storing that element's address.
When I write it as " p++; " it does not work, whereas if I write it as *p=*p+1
it works.
*p=*p+1; // this increments the value
*p++; //while this does not
I am expecting both ways to work
Upvotes: 0
Views: 178
Reputation: 120
#include <iostream>
using namespace std;
int main (int argc, char *argv[])
{
int numbers[] = { 100, 200, 300, 400, 500, 600 };
int *p1 = &numbers[0];
int *p2 = &numbers[2];
int *p3 = &numbers[4];
*p1 = *p1 + 1;
*p2 = *p2++;
++*p3;
cout << numbers[0] << " " << numbers[1] << " " << numbers[2] << " " << numbers[3] << " " << numbers[4] << " " << numbers[5];
}
Running this through Xcode gives me a clue as to what's going wrong, it says: "temp/test.cxx:11:12: warning: unsequenced modification and access to 'p2' [-Wunsequenced]".
The output is 101 200 300 300 501 600
.
The first method works, as you said in your question.
The second does something completely different from what you were expecting: it takes the value pointed to by p2 (300) then increments the pointer and saves the value back to that new address.
The third example with p3 is closer to what you're trying to achieve I think.
Upvotes: 0
Reputation: 37488
operator ++
has higher precedence than dereference so *p++
increments the pointer and then performs dereference. If you want to increment the value it initially points to then you need to add parentheses: (*p)++;
Upvotes: 5