Why I can not do * value ++; to increase it to the value in this memory location?

I understand that for work it must be

void increment(int *value) { (*value)++; } 

This is because it needs brackets because of how priority works (correct me if I am wrong). But why, when I do the following, a compilation error does not occur? The value does not change, what should be expected because there are no brackets, but what exactly does this change?

 void increment(int *value) { *value++; } 
+7
c ++ pointers
source share
4 answers

value is a pointer to an integer. Pointer arithmetic rules say that if you perform an operation of type value++ , then it will point to value + sizeof(int) (in terms of bytes).

What happens here, you would dereference value to get some rvalue value that you just throw away, and then incrementing value (and not what it points to, rather, the pointer itself).

+7
source share
 *value++; 

It undoes the reference to the value at the location that value points to, and increments the value pointer due to the post-increment. In fact, this is the same as value++ , since you discard the value returned by the expression.

 But how come when I do the following, no compile error happens? 

Because it is a valid statement, and you simply discard the value returned by the expression. Similarly, you can have statements like:

 "Random string"; 42; 

and they are valid and will compile a fine (but worthless).

We discard the many return values ​​of standard library functions. For example. memset() returns void * to the memory that was installed, but we rarely use it. It is not so intuitive, but it is absolutely true.

+2
source share

while not quite the answer: from K & RC memcopy can be implemented in this way. if you understand what happened, you can answer your own question.

 void *memcpy(char *ptr1, char *ptr2, size_t n) { void *ret = ptr1; while (n >0) { *ptr1++ = *ptr2++; n--; } return ret; } 
0
source share

According to precedence operators,

++ precedes *

Therefore, it runs as

value++ and * . Effectively *(value++)

value++ will return you the address value + (size of datatype pointed at) ie value + (size of int) in this case.

If your value points to an array, you are probably collecting the value of the garbage and casting it.

0
source share

All Articles