ipkiss ipkiss - 19 days ago 5
C Question

Pointer Arithmetic: ++*ptr or *ptr++?

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?

Can anyone explain, please?

Thanks a lot.

Answer

These statements produce different results because of the way in which the operators bind. In particular, the postfix ++ operator has the same precedence as *. Thus

++*ptr

is parsed as

++(*ptr)

meaning "increment the value pointed at by ptr," while

*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!

Comments