Berat24
Berat24

Reputation: 33

Confusion over pointer index operator

I am a little bit confused about pointer index operator in C. I will try to explain my question with an example:

int array[5] = {1,2,3,4,5};
int *p;
p = array;
p[2]++;

In the fourth line, I know that it increments the second index of array. However, when I see an index operator, I convert it.

For instance, I converted p[2]++ to *(p+2)++. According to the operator precedence table, in the statement of *(p+2)++, the increment and dereferencing operators have the same precedence, but increment takes precedence due to right associativity. Therefore, it becomes *(p+3). Then, this statement cannot change any value and just points third index of array.

Why does p[2]++ increment the second index of the array? What is wrong in my perspective?

Upvotes: 2

Views: 293

Answers (3)

wznmickey
wznmickey

Reputation: 135

In math, if a=b+c,then a*d is not b+c*d but (b+c)*d. Likely, p[2] is not be taken by *(p+2) but (*(p+2)) to avoid any change on precedence.

Upvotes: 0

vilaor
vilaor

Reputation: 41

As already commented p[2]++ can be converted to (*(p+2))++, because p[2] is the element you want to increment. Think that when incrementing indexes is usually done like p[i++]

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361977

p[2]++ is equivalent to (*(p+2))++, not *(p+2)++. You need an extra set of parentheses to maintain the precedence from the original expression.

Without them you've got *(p+2)++ which, as you've noted, is equivalent to *((p+2)++). This has a different meaning from the original expression since it splits up the +2 and the *. They need to be done in the same step since [2] is a single atomic operation.

Upvotes: 4

Related Questions