1

I've got void pointer which I want to do pointer arithmetic on it. to do so, I want to cast it to a char pointer.

( char * ) buf += current_size;

However when I do so, I get the following error:

error: lvalue required as left operand of assignment

I tried also adding parenthesis on the the whole left side, with no success. Why do I get this ?

3 Answers 3

5

You can avoid the warning by writing the assignment operator out:

buf = (char *)buf + current_size;

Part of the reason you get the warning is that sizeof(void) is undefined and you cannot do arithmetic on void *. Beware: GCC has an extension whereby it treats the code as if sizeof(void) == 1, but that is not in the C standard.

The cast on the LHS of the assignment has no effect on the assignment.

Sign up to request clarification or add additional context in comments.

2 Comments

Should that be "...you cannot do arithmetic on void"? If it were a pointer with a type, then you could do math on it.
@jww: you can't do arithmetic on void either.
5

Why do I get this

Simply because the language rules state that a cast does not produce an lvalue even if the operand is one.

ISO/IEC 9899:201x - n1570

In a footnote, page 91

A cast does not yield an lvalue.

Comments

4

Because it's invalid, you can't do this. If you want to achieve this, either

declare buf as a char pointer; or use a temporary variable:

char *tmp = buf; // note you don't need the casting, void * works with everything
tmp += current_size;
buf = tmp;

Edit: as others also suggested, you can even remove that ugly tmp:

buf = (char *)buf + current_size;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.