The standard way:
#include <vector>
#include <string>
std::vector<unsigned char> to_vector(std::string const& str)
{
// don't forget the trailing 0...
return std::vector<unsigned char>(str.data(), str.data() + str.length() + 1);
}
int main()
{
std::string str = "abcde";
auto v = to_vector(str);
}
A way that uses variable-length array extensions, available on some compilers:
#include <algorithm>
#include <string>
int main()
{
std::string str = "abcde";
unsigned char v[str.length() + 1];
std::copy(str.data(), str.data() + str.length() + 1, v);
}
But note:
main.cpp:14:37: warning: ISO C++ forbids variable length array 'v' [-Wvla]
unsigned char v[str.length() + 1];
^
... and here's another way which ensures that we're using a reference to an array. Note that the reference is only valid in the current thread, and only until the next call to to_array(). But note that this is all un-necessary.
#include <vector>
#include <string>
#include <iostream>
unsigned char (& to_array(std::string const& str))[]
{
static thread_local std::vector<unsigned char> result;
result.assign(str.data(), str.data() + str.length() + 1);
return reinterpret_cast<unsigned char (&)[]>(*result.data());
}
extern "C" void foo(unsigned char p[]) { }
int main()
{
std::string str = "abcde";
unsigned char (&v)[] = to_array(str);
foo(v); // ok
foo(reinterpret_cast<unsigned char*>(str.data())); // also ok!
}