ipkiss ipkiss - 1 year ago 99
C Question

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

I am learning C language and quite confused the differences between

for example:

int x = 19;
int *ptr = &x;

I know
produce different results but I am not sure why is that?

Can anyone explain, please?

Thanks a lot.

Answer Source

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


is parsed as


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




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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download