How do I copy a char* to a unsigned char* correctly in C. Following is my code
int main(int argc, char **argv)
{
unsigned char *digest;
digest = malloc(20 * sizeof(unsigned char));
strncpy(digest, argv[2], 20);
return 0;
}
I would like to correctly copy char* array to unsigned char* array. I get the following warning using the above code
warning: pointer targets in passing argument 1 of âstrncpyâ differ in signedness
EDIT: Adding more information, My requirement is that the caller provide a SHA digest to the main function as a string on command line and the main function internally save it in the digest. SHA digest can be best represented using a unsigned char.
Now the catch is that I can't change the signature of the main function (** char) because the main function parses other arguments which it requires as char* and not unsigned char*.
To avoid the compiler warning, you simply need:
strncpy((char *)digest, argv[2], 20);
But avoiding the compiler warning is often not a good idea; it's telling you that there is a fundamental incompatibility. In this case, the incompatibility is that char
has a range of -128 to +127 (typically), whereas unsigned char
is 0 to +255.