If I have a void * x, but I want to cast it to a char *, so that the ++ operator will make it point to the next byte and not the next 4 byte block.
However, when I do:
(char *) x -= byte_length;
The compiler complains:
Error, lvalue required as left value of assignment.
Where am I going wrong please? Thanks.
I would do it like this:
x = (char*)x - byte_length;
Cast x
to char*
, then apply the offset, then assign back to x
. Since void*
is assignment compatible with all pointer types no further cast is needed.
(char *)x
evaluates to a temporary with the same value as x
but a different type. The compiler won't allow -=
on a temporary. Do
x = (char *)x - byte_length;
The situation is analogous to the following:
short x = 0;
(long)x += 1; // invalid; (long)x is a temporary
x = (long)x + 1; // works
Do something like this:
void* x;
char* cx = (char*)x;
cx -= byte_length;
x = cx;
(char*) x -= byte_length;
In this statement, (char*) x
creates a temporary value with char*
as type. You can only assign to variables, or more precisely, references (or an lvalue
according to your compiler).
One way to get a reference to it is casting the address of x to char*
and dereferencing that:
*(char*) &x -= byte_length;
(char*)x
is a temporary value that has not address in memory. You can't do a --
to it, for the same reason that if you have int i
, you can't do (i+5)++
.
You should do x=(char*)x-byte_length;
instead.
See also http://c-faq.com/ptrs/castincr.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.