指针运算:++ * PTR或* PTR ++? [英] Pointer Arithmetic: ++*ptr or *ptr++?
问题描述
我学习C语言和相当混乱之间的差异 ++ * PTR
和 * PTR ++
。
例如:
I am learning C language and quite confused the differences between ++*ptr
and *ptr++
.
for example:
int x = 19;
int *ptr = &x;
我知道 ++ * PTR
和 * PTR ++
产生不同的结果,但我不知道这是为什么?
I know ++*ptr
and *ptr++
produce different results but I am not sure why is that?
任何人能解释吗?
非常感谢。
推荐答案
这些语句产生的,因为其中的运营商绑定的方式不同的结果。尤其是, ++
具有相同的precedence为 *
,但运营商绑定从右到左(请参见更多信息此表)。因此,
These statements produce different results because of the way in which the operators bind. In particular, ++
have the same precedence as *
, but the operators bind right-to-left (see this table for more info). Thus
++*ptr
被解析为
++(*ptr)
,意思是在增加通过 PTR
值指出,同时,
*ptr++
办法
*(ptr++)
这意味着增量 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).
在您所描述的情况下,你可能想要写 ++ * PTR
,这将增加 X
间接通过 PTR
。写 * PTR ++
将是危险的,因为它会游行 PTR
转发过去 X
,自 X
不是数组指针会在某处内存中晃来晃去的一部分(可能是在其本身上!)
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!)
希望这有助于!
这篇关于指针运算:++ * PTR或* PTR ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!