Why is *p++ different from *p += 1?

后端 未结 4 1210
天涯浪人
天涯浪人 2020-12-04 15:25

Consider:

void foo1(char **p) { *p++; }
void foo2(char **p) { *p += 1; }

and

char *s = \"abcd\";
char *a = s; 
foo1(&a)         


        
4条回答
  •  心在旅途
    2020-12-04 15:51

    The key is the precedence of the += and the ++ operator. The ++ has a higher precedence than the += (in fact, assignment operators have the second lowest precedence in C), so the operation

    *p++
    

    means dereference the pointer, then increment the pointer itself by 1 (as usually, according to the rules of pointer arithmetic, it's not necessarily one byte, but rather sizeof(*p) regarding the resulting address). On the other hand,

    *p += 1
    

    means increment the value pointed to by the pointer by one (and do nothing with the pointer itself).

提交回复
热议问题