cpointerscastingimplementationmemcpy

Why cast 'void*' pointers to 'unsigned char *' in memcpy's implementation?


I was looking at an implementation of memcpy, and was wondering, why do you need to cast the pointer pDst to an unsigned char *? Same for pSrc?

void memcpy( void *pDst, void *pSrc, int len )
{
    int i;

    if( pDst == NULL || pSrc == NULL )
        return;

    for( i=0; i<len; i++ ) {
        ((unsigned char*)pDst)[i] = ((unsigned char*)pSrc)[i];
    }
}

Solution

  • A pointer to void is a useful shorthand for saying "pointer to anything" but the compiler conversely doesn't therefore know how big the thing being pointed to is.

    So when you do any kind of arithmetic on it (like indexing it as an array) you must use some explicit size. In this case, because you're trying to do a byte-by-byte copy, you use a cast to unsigned char which is generally a way of saying "1 byte".

    (This might seem at first blush like it's always true. But in cases besides memcpy, you could be pointing to something larger, like a structure of some sort, then the index/arithmetic would actually be referring to increments of that structure's size so you could skip from one structure to the next.)