user1431282
user1431282

Reputation: 6835

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];
    }
}

Upvotes: 2

Views: 3002

Answers (3)

user703016
user703016

Reputation: 37945

Because you can't dereference a void*. You must explicitly tell the compiler how many bytes you want it to copy. In the case of an unsigned char, that would be 1.

Upvotes: 4

La VloZ
La VloZ

Reputation: 112

you must cast it to char * or to unsigned char * to tell to the compiler how many of bytes must add, in char * or unsigned char * case will add 1 byte. next element = actually element + (i * the length of the type) and void * is a type of nothing so you must cast it to char *

Upvotes: 0

Ben Zotto
Ben Zotto

Reputation: 71008

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

Upvotes: 8

Related Questions