lvalue required on incrementing a void pointer even after proper casting
Вопрос
I am implementing memset()
method. Below is the code snippet:
void my_memset(void* ptr, int n, size_t size)
{
unsigned int i;
for( i = 0; i < size; ++i, ++(char*)ptr )
*(char*)ptr = n;
}
I am getting the error as:
prog.cpp: In function ‘void my_memset(void*, int, size_t)’:
prog.cpp:8: error: lvalue required as increment operand
When i change the type of ptr from void*
to int*
, it compiles successfully.
Why it is asking for lvalue?
Решение
void my_memset(void* ptr, int n, size_t size)
{
char *cptr = (char *)ptr;
char *limit = cptr + size;
for(; cptr < limit; cptr++) {
*cptr = n;
}
}
you can't increment through a cast like that, and you shouldn't want to.
Другие советы
The result of a type-casting is not an lvalue. Say,
float f = 3.14;
++((int)f);
here we're applying ++
operator to an int value, but we don't have an int variable to increment. So in general case, type-casting cannot produce lvalues.
You can't for the same reason you can't do this:
++someFunction();
or
++(a + b);
The cast is an expression and the results of expressions don't have writable storage.
Не связан с StackOverflow