Reputation: 2404
My CS course is taking a bit of a turn from Java to C. I'm busy going over pointers at the moment and I have come across that the ++ operator for incrementing doens't work when dereferencing. This is more just a curiosity question than anything else. Just not used to the pointers concept just yet. Am I just doing something wrong or is it something to do with pointers?
For example:
*pointer++; Will not increment the value.
*pointer+=1; Will increment the value.
Thanks in advance!
Upvotes: 2
Views: 256
Reputation: 5168
*pointer++
increments the pointer
variable, not value pointed by it.
int array[4] = {3,5,7,9};
int *pointer = array;
// *pointer equals 3
*pointer++;
// *pointer now equals 5
Upvotes: 4
Reputation: 58291
*pointer++;
is almost equivalent to:
*pointer;
pointer = pointer + 1;
Why its so?
In expression *pointer++;
, ++
is postfix operator, so fist *
deference operation performed then ++
increments value of pointer
(and not increments value).
Whereas *pointer += 1
is just equivalent to:
*pointer = *pointer + 1;
that increments value pointed by pointer
.
Upvotes: 2
Reputation: 726987
This has to do with precedence of the operators: post-increment ++
has higher precedence than the dereference operator *
, while +=
has lower precedence in the table of operator precedences. That is why in the first example ++
is applied to the pointer which is dereferenced afterwards, while in the second example += 1
is applied to the result of dereference.
Upvotes: 2
Reputation: 145899
*pointer++;
is equivalent to
*(pointer++); // pointer is incremented
and not to
(*pointer)++; // pointee is incremented
Upvotes: 4
Reputation: 1277
When you want to increment the value you have to make sure you use parenthesis.
(*pointer)++;
Upvotes: 5