Home:ALL Converter>Is it safe to convert char * to const unsigned char *?

Is it safe to convert char * to const unsigned char *?

Ask Time:2017-08-30T10:54:48         Author:Sato

Json Formatter

We are using char * and the lib we use is using const unsigned char *, so we convert to const unsigned char *

// lib
int asdf(const unsigned char *vv);

//ours
char *str = "somestring";
asdf((const unsigned char*)str);

Is it safe? any pitfall?

Author:Sato,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/45951161/is-it-safe-to-convert-char-to-const-unsigned-char
lwzhuo :

it is safe.\n\nchar *str = \"somestring\";\n\n\nstr is a constant,you could change str point to another string:\n\nstr = \"some\";//right\n\n\nbut you can't change the string which str is pointing now\n\nstr[0]='q';//wrong\n\n\nso it is safe to use const to convert a constant to constant\n\nif the asdf() only use to show the string,likes printf() or puts() ,you no need to const,because you are not change the string.\n\nif you use const it will be safer.when you implementing the asdf(),it will make sure you can't write the wrong code likes \"str[0]='q';\" because you can't compile it.\n\nif there are no const,you will find the error until you running the program.",
2017-08-30T03:50:48
Carl Norum :

If it's being treated as a string by that interface, there should be no problem at all. You don't even need to add the const in your cast if you don't want to - that part is automatic.",
2017-08-30T02:56:37
o11c :

Technically, it is always safe to convert pointers from one type to another (except between function pointers and data pointers, unless your implementation provides an extension that allows that). It's only the dereferencing that is unsafe.\n\nBut dereferencing a pointer to any signedness of char is always safe (from a type aliasing perspective, at least).",
2017-08-30T03:02:29
yy