Put bytes from unsigned char array to std::string using memcpy() function
Since we're just constructing the string, there is a std::string
constructor that takes two iterators:
template< class InputIt >
basic_string( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
which we can provide:
std::string newString(&bytes[startIndex], &bytes[startIndex] + length);
If we're not constructing the string and are instead assigning to an existing one, you should still prefer to use assign()
. That is precisely what that function is for:
oldString.assign(&bytes[startIndex], &bytes[startIndex] + length);
But if you really insist on memcpy()
for some reason, then you need to make sure that the string actually has sufficient data to be copied into. And then just copy into it using &str[0]
as the destination address†:
oldString.resize(length); // make sure we have enough space!
memcpy(&oldString[0], &bytes[startIndex], length);
†Pre-C++11 there is technically no guarantee that strings are stored in memory contiguously, though in practice this was done anyway.