如何在 C++ 中将 const char* 复制到 uint8_t []?

Suk*_*and 1 c++

在下面的例子中

const char* msg1 = "hello how are you";
Run Code Online (Sandbox Code Playgroud)

我想复制到 uint8_t msg2[]

如何将 msg1 值复制到 msg2 中?

Joh*_*ord 5

由于这是一个'C'ish 问题,我使用了 C 风格的转换。

const char* msg1 = "hello how are you";
size_t length = strlen(msg1) + 1;

const char* beg = msg1;
const char* end = msg1 + length;

uint8_t* msg2 = new uint8_t[length];

size_t i = 0;
for (; beg != end; ++beg, ++i)
{
    msg2[i] = (uint8_t)(*beg);
}

std::cout << msg1 << "\n\n";
std::cout << msg2 << "\n\n";

delete[] msg2;
Run Code Online (Sandbox Code Playgroud)

输出:

hello how are you

hello how are you
Run Code Online (Sandbox Code Playgroud)