Memcpy Casting C

c

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

Problem

I'm a bit rusty on C and I was looking at an implementation of memcpy. I was wondering why do you need to cast the pointer pDst to an unsigned character? 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]; } } ```

Original source