指针运算:++*ptr 还是 *ptr++? [英] Pointer Arithmetic: ++*ptr or *ptr++?
问题描述
我正在学习 C 语言,对 ++*ptr
和 *ptr++
之间的区别感到很困惑.
I am learning C language and quite confused the differences between ++*ptr
and *ptr++
.
例如:
int x = 19;
int *ptr = &x;
我知道 ++*ptr
和 *ptr++
产生不同的结果,但我不知道为什么会这样?
I know ++*ptr
and *ptr++
produce different results but I am not sure why is that?
推荐答案
由于运算符绑定的方式不同,这些语句会产生不同的结果.特别地,前缀++
运算符与*
具有相同的优先级,并且它们从右到左关联.于是
These statements produce different results because of the way in which the operators bind. In particular, the prefix ++
operator has the same precedence as *
, and they associate right-to-left. Thus
++*ptr
被解析为
++(*ptr)
意思是增加ptr
指向的值,".另一方面,后缀 ++
运算符比解引用运算符 *
具有更高的优先级.之前
meaning "increment the value pointed at by ptr
,". On the other hand, the postfix ++
operator has higher precedence than the dereferrence operator *
. Thefore
*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
,它会通过 ptr
间接增加 x
.编写 *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屋!