Problem
The problem is that (char*)ptr will not give an lvalue value, which means that the value cannot be changed - you can see it as a temporary result of the cast, the cast will give an rvalue of type char* .
This is semantically the same as if you had the example below, the cast gives a temporary value, this value cannot be assigned a new value.
int x = 123; (float)x += 0.12f;
Decision
In your question, you stated that you already know a workaround to this problem, but I would like to write a solution explicitly to show how you can change the ptr value, even if the cast gives unmodifiable values.
- Take the address of the pointer to void,
- sends this address to a pointer to a pointer to a char,
- dereference this pointer by pointing to a pointer to char,
- change this lvalue value as if the original
void* was of type char*
*((char**)&ptr) += numbytes; // make `ptr` move forward `numbytes`
( Note : when dereferencing a pointer, you get an lvalue value, otherwise it would be impossible to change the value of the pointer to a value located at the address stored in the pointer.)
source share