I want an std::string object (such as a name) to a uint8_t array in C++. The
function reinterpret_cast<const uint8_t*>
rejects my string. And since I'm coding using NS-3, some warnings are being interpreted as errors.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you want a pointer to the string
's data:
reinterpret_cast<const uint8_t*>(&myString[0])
If you want a copy of the string
's data:
std::vector<uint8_t> myVector(myString.begin(), myString.end());
uint8_t *p = &myVector[0];
回答2:
String objects have a .c_str()
member function that returns a const char*
. This pointer can be cast to a const uint8_t*
:
std::string name("sth");
const uint8_t* p = reinterpret_cast<const uint8_t*>(name.c_str());
Note that this pointer will only be valid as long as the original string object isn't modified or destroyed.