C语言 指针指向的 int 的增量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3655728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
increment value of int being pointed to by pointer
提问by joels
I have an intpointer (i.e., int *count) that I want to increment the integer being pointed at by using the ++operator. I thought I would call:
我有一个int指针(即int *count),我想通过使用++运算符来增加指向的整数。我以为我会打电话:
*count++;
However, I am getting a build warning "expression result unused". I can: call
但是,我收到一个构建警告“表达式结果未使用”。我可以打电话
*count += 1;
But, I would like to know how to use the ++operator as well. Any ideas?
但是,我也想知道如何使用++运算符。有任何想法吗?
回答by Doug T.
The ++ has equal precedence with the * and the associativity is right-to-left. See here.It's made even more complex because even though the ++ will be associated with the pointerthe increment is applied after the statement's evaluation.
++ 与 * 具有相同的优先级,并且关联性是从右到左的。看到这里。它变得更加复杂,因为即使 ++ 将与指针相关联,但在语句评估之后应用增量。
The order things happen is:
事情发生的顺序是:
- Post increment, remember the post-incremented pointer address value as a temporary
- Dereference non-incremented pointer address
- Apply the incremented pointer address to count, count now points to the next possible memory address for an entity of its type.
- 后增量,记住后增量的指针地址值作为临时
- 取消引用非递增指针地址
- 将递增的指针地址应用于计数,计数现在指向其类型实体的下一个可能的内存地址。
You get the warning because you never actually use the dereferenced value at step 2. Like @Sidarth says, you'll need parenthesis to force the order of evaluation:
您收到警告是因为您从未在第 2 步实际使用取消引用的值。就像@Sidarth 所说,您需要括号来强制计算顺序:
(*ptr)++
回答by Sidharth Panwar
Try using (*count)++. *count++might be incrementing the pointer to next position and then using indirection (which is unintentional).
尝试使用(*count)++. *count++可能是将指针增加到下一个位置,然后使用间接(这是无意的)。

