Search code examples
cpointerscompilationcompiler-errorsdereference

Using Increment operator with de-referencing in C


To my function i get a void pointer, I would like to point to the next location considering the incoming pointer is of char type.

int doSomething( void * somePtr )
{
   ((char*)somePtr)++; // Gives Compilation error
}

I get the following compilation error:

Error[Pe137]: expression must be a modifiable lvalue

Is this an issue with the priority of operators?


Solution

  • A cast does not yield an lvalue (see section 6.5.4 footnote 104 of C11 standard), therefore you can't apply post increment ++ operator to its result.

    c-faq: 4.5:

    In C, a cast operator does not mean "pretend these bits have a different type, and treat them accordingly"; it is a conversion operator, and by definition it yields an rvalue, which cannot be assigned to, or incremented with ++. (It is either an accident or a deliberate but nonstandard extension if a particular compiler accepts expressions such as the above.)

    Try this instead

    char *charPtr = ((char*)somePtr);
    charPtr++;