void foo(void *ptr, int numBytes)
{
(char*)ptr += numBytes;
}
This doesn't compile in C. I know the alternative. But why does this not work? What is the problem?
The problem
The problem is that (char*)ptr
will not yield an lvalue, meaning that the value cannot be modified - one can see it as a temporary result of the cast, the cast will yield a rvalue of type char*
.
It's semantically the same as if you'd have the below example, a cast yields a temporary value, such a value cannot be assigned a new value.
int x = 123;
(float)x += 0.12f; /* (1), illegal */
/* ^-- sementically equivalent to `123.f += 0.12f` */
Solution
In your question you have stated that you already know a workaround to this problem, but I'd like to explicitly write the solution to show how one can modify the value of ptr
even when casts yields non-modifiable values.
void*
was of type char*
*((char**)&ptr) += numbytes; // make `ptr` move forward `numbytes`
( Note: When dereferencing a pointer you get an lvalue, otherwise it would be impossible to change the value of the pointed to value located at an address stored in a pointer. )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With