cgccpointer-arithmeticgcc-pedantic

-Wpedantic wrong type argument to increment after casting


I have a code like

while (n--)
{
  *((char*)dest++) = *((char*)src++);
}

where dest and src are void pointers and n a size. The goal is to re-implement a memcpy function. When compiling this code with gcc, everything works great, but when I add the -Wpedantic flag I have four warnings "wrong type argument to increment".

Google tells me that it happens when trying to use arithmetic on void pointers, because gcc treats void type as being a 1 byte type in this case, but legacy compilers shoud not. I then have to cast the pointer to a char pointer but as you can see I already did it!

Any idea?


Solution

  • Casting (void) dest and src to unsigned char * before you use them gives the cleanest code (at the cost of two pointer variables on the stack).

    unsigned char * dest_p = (unsigned char *)dest;
    unsigned char * src_p  = (unsigned char *)src;
    
    while ( n-- )
    {
        *dest_p++ = *source_p++;
    }
    

    (Why unsigned? Because that's how the standard explicitly defines it. ;-) )