increment value of int being pointed to by pointer

安稳与你 提交于 2019-11-27 12:38:17

问题


I have an int pointer (i.e., int *count) that I want to increment the integer being pointed at by using the ++ operator. I thought I would call:

*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?


回答1:


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 pointer the increment is applied after the statement's evaluation.

The order things happen is:

  1. Post increment, remember the post-incremented pointer address value as a temporary
  2. Dereference non-incremented pointer address
  3. 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:

 (*ptr)++



回答2:


Try using (*count)++. *count++ might be incrementing the pointer to next position and then using indirection (which is unintentional).



来源:https://stackoverflow.com/questions/3655728/increment-value-of-int-being-pointed-to-by-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!