I'm trying to create my own versions of C functions and when I got to memcpy and memset I assumed that I should cast the destination and sources pointers to char *. However, I've seen many examples where the pointers were casted to unsigned char * instead. Why is that?
void *mem_cpy(void *dest, const void *src, size_t n) {
if (dest == NULL || src == NULL)
return NULL;
int i = 0;
char *dest_arr = (char *)dest;
char *src_arr = (char *)src;
while (i < n) {
dest_arr[i] = src_arr[i];
i++;
}
return dest;
}
It doesn't matter for this case, but a lot of folks working with raw bytes will prefer to explicitly specify
unsigned char(or withstdint.htypes,uint8_t) to avoid weirdness if they have to do math with the bytes.charhas implementation-defined signedness, and that means, when the integer promotions & usual arithmetic conversions are applied, acharwith the high bit set is treated as a negative number if signed, and a positive number if unsigned.While neither behavior is necessarily wrong for a given problem, the fact that the behavior can change between compilers or even with different flags set on the same compiler, means you often need to be explicit about signedness, using either
signed charorunsigned charas appropriate, and 99% of the time, the behaviors ofunsigned charare what you want, so people tend to default to it even when it's not strictly required.