Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment value of int being pointed to by pointer

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?

like image 621
joels Avatar asked Sep 07 '10 04:09

joels


People also ask

How do you increment the value of a int pointer?

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

When we add 1 to the pointer its value is incremented by?

Pointer Arithmetic Unlike regular numbers, adding 1 to a pointer will increment its value (a memory address) by the size of its underlying data type.

What will happen if an integer number is added to a pointer?

Pointer arithmetic and arrays. Add an integer to a pointer or subtract an integer from a pointer. The effect of p+n where p is a pointer and n is an integer is to compute the address equal to p plus n times the size of whatever p points to (this is why int * pointers and char * pointers aren't the same).


1 Answers

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)++ 
like image 101
Doug T. Avatar answered Nov 04 '22 11:11

Doug T.