为什么* P ++从* P + = 1有什么不同? [英] Why is *p++ different from *p += 1?

查看:156
本文介绍了为什么* P ++从* P + = 1有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

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

char *s = "abcd";
char *a = s; 
foo1(&a); 
printf("%s", a); //abcd

但如果我用 foo2的()而不是:

char *a = s; 
foo2(&a); 
printf("%s", a); //bcd

有人能解释一下吗?

Can someone explain it?

推荐答案

关键是的precedence的 + = ++ 运营商。在 ++ 具有更高的precedence比 + = (事实​​上,赋值运算符有第二低$中的p C $ pcedence),所以操作

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++

意味着取消引用指针,然后递增指针的本身按1(如通常,根据指针运算规则,它不一定是一个字节,而的sizeof( * 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).

这篇关于为什么* P ++从* P + = 1有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆