Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ style cast from unsigned char * to const char *

I have:

unsigned char *foo();
std::string str;
str.append(static_cast<const char*>(foo()));

The error: invalid static_cast from type ‘unsigned char*’ to type ‘const char*’

What's the correct way to cast here in C++ style?

like image 766
jackhab Avatar asked Mar 18 '09 16:03

jackhab


3 Answers

char * and const unsigned char * are considered unrelated types. So you want to use reinterpret_cast.

But if you were going from const unsigned char* to a non const type you'd need to use const_cast first. reinterpret_cast cannot cast away a const or volatile qualification.

like image 163
Brian R. Bondy Avatar answered Nov 17 '22 15:11

Brian R. Bondy


Try reinterpret_cast

unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));
like image 56
JaredPar Avatar answered Nov 17 '22 15:11

JaredPar


reinterpret_cast

like image 52
Ruben Bartelink Avatar answered Nov 17 '22 15:11

Ruben Bartelink