I am learning C language and quite confused the differences between ++*ptr
and *ptr++
.
For example:
int x = 19;
int *ptr = &x;
I know ++*ptr
and *ptr++
produce different results but I am not sure why is that?
These statements produce different results because of the way in which the operators bind. In particular, the prefix ++
operator has the same precedence as *
, and they associate right-to-left. Thus
++*ptr
is parsed as
++(*ptr)
meaning "increment the value pointed at by ptr
,". On the other hand, the postfix ++
operator has higher precedence than the dereferrence operator *
. Thefore
*ptr++
means
*(ptr++)
which means "increment ptr
to go to the element after the one it points at, then dereference its old value" (since postfix ++
hands back the value the pointer used to have).
In the context you described, you probably want to write ++*ptr
, which would increment x
indirectly through ptr
. Writing *ptr++
would be dangerous because it would march ptr
forward past x
, and since x
isn't part of an array the pointer would be dangling somewhere in memory (perhaps on top of itself!)
Hope this helps!