Search code examples
cpointersvoidc89pointer-arithmetic

increment of void* type-casted as char* fails


In a function like this:

char nextchr (void* p)
{
    ((char*)p)++;

    return *(((char*)p));
}

That is supposed to return the second character of a string literal passed as the argument p simply fails to do that.

Why that could be?


Solution summery:

@M.M : ++ requires a lvalue (left-handed value) for it to apply to and the result from the type-cast isn't that.

@OP Update : Some compilers (generally /old C89/ /compilers/ like mine) may allow ((char*)source)++; /as long as it is not passed as argument to a function/ even though it is illegal and proven as illegal by the C standards.


Solution

  • ++ requires an lvalue. Your code could be:

    char *c = p;
    ++c;
    return *c;
    

    although it would be a lot simpler to write return ((char *)p)[1];