[英]Why don't compound assignment or iterative operators work on dereferenced pointers
If I want to increment a pointer that's referencing a the location of an int
I can't use these methods: 如果要增加引用
int
位置的指针,则不能使用以下方法:
*Pntr +=1;
*Pntr++;
However, using this method works with no problems: 但是,使用此方法不会有任何问题:
*Pntr = *Pntr + 1;
What's happening that causes these shorthand methods not to work. 正在发生的事情导致这些速记方法不起作用。 (Also must point out I'm using Visual Studio and it acts weird at times so I think I should mention that)
(还必须指出,我使用的是Visual Studio,有时它的行为很怪异,所以我想我应该提一下)
*Pntr +=1;
This increments the value the pointer is pointing to. 这将增加指针指向的值。
*Pntr++;
This is the same as: 这与:
*(Pntr++);
Which increments the pointer, dereferences the original value of the pointer, and discards the retrieved value. 这将增加指针,取消引用指针的原始值并丢弃检索到的值。
*Pntr = *Pntr + 1;
This, like the first line, increments the value the pointer is pointing to. 就像第一行一样,它增加了指针指向的值。
If I want to increment a pointer that's referencing a the location of an int... [emphasis added]
如果我想增加与真实引用一个int的位置的指针 ...... [强调]
Note that when you increment a pointer, it gets incremented in steps of the object size that the pointer can point to . 请注意,当您增加一个指针时, 它会以该指针可以指向的对象大小的步长递增 。
Since you have mentioned - 既然您提到-
using this method works with no problems:
使用此方法没有问题:
*Pntr = *Pntr + 1;
So, it looks like you want to increase the value at location, pointed by Pntr
, by 1
. 因此,您似乎想将
Pntr
指向的Pntr
的值增加1
。
The precedence of postfix ++
operator is higher than unary *
operator (check operator precedence table). 后缀
++
运算符的优先级高于一元*
运算符(检查运算符优先级表)。 So, the expression 所以,表达
*Pntr++;
will be evaluated as 将被评估为
*(Pntr++);
which will move the pointer Pntr
by size of int
and then dereference it. 这将使指针
Pntr
移动int
的大小,然后取消对其的引用。
To increment the value of pointer, you can do: 要增加指针的值,可以执行以下操作:
(*Pntr)++;
You can also use the prefix ++
operator: 您还可以使用前缀
++
运算符:
++*Pntr;
The expression 表达方式
*Pntr +=1;
is same as 与...相同
*Pntr = *Pntr + 1;
and both will increase the value at location pointed by Pntr
by 1
. 并且两者都会使
Pntr
指向的位置的值增加1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.