-Wpedantic wrong type argument to increment after casting

我与影子孤独终老i 提交于 2019-12-11 03:59:39

问题


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?


回答1:


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. ;-) )



来源:https://stackoverflow.com/questions/26033338/wpedantic-wrong-type-argument-to-increment-after-casting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!