c++ - Put bytes from unsigned char array to std::string using memcpy() function -


i have std::string variable. , need put bytes array of unsigned chars it. know first byte , the legth.

i can use std::string::assign function. i've done it.

but want solve issue in right way using memcpy function.

std::string newstring; memcpy(&newstring, &bytes[startindex], length); 

i know wrong. have researched , found ideas using std::vector.

please me find elegant solution issue.

since we're constructing string, there std::string constructor takes 2 iterators:

template< class inputit > basic_string( inputit first, inputit last,                const allocator& alloc = allocator() ); 

which can provide:

std::string newstring(&bytes[startindex], &bytes[startindex] + length); 

if we're not constructing string , instead assigning existing one, should still prefer use assign(). precisely function for:

oldstring.assign(&bytes[startindex], &bytes[startindex] + length); 

but if insist on memcpy() reason, need make sure string has sufficient data copied into. , copy using &str[0] destination address:

oldstring.resize(length); // make sure have enough space! memcpy(&oldstring[0], &bytes[startindex], length); 

pre-c++11 there technically no guarantee strings stored in memory contiguously, though in practice done anyway.


Comments