Difference between *ptr += 1 and *ptr++ in C

前端 未结 5 646
星月不相逢
星月不相逢 2020-12-23 19:58

I just started to study C, and when doing one example about passing pointer to pointer as a function\'s parameter, I found a problem.

This is my sample code :

5条回答
  •  伪装坚强ぢ
    2020-12-23 20:45

    The difference is due to operator precedence.

    The post-increment operator ++ has higher precedence than the dereference operator *. So *ptr++ is equivalent to *(ptr++). In other words, the post increment modifies the pointer, not what it points to.

    The assignment operator += has lower precedence than the dereference operator *, so *ptr+=1 is equivalent to (*ptr)+=1. In other words, the assignment operator modifies the value that the pointer points to, and does not change the pointer itself.

提交回复
热议问题