Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying non null-terminated unsigned char array to std::string

If the array was null-terminated this would be pretty straight forward:

unsigned char u_array[4] = { 'a', 's', 'd', '\0' }; std::string str = reinterpret_cast<char*>(u_array); std::cout << "-> " << str << std::endl; 

However, I wonder what is the most appropriate way to copy a non null-terminated unsigned char array, like the following:

unsigned char u_array[4] = { 'a', 's', 'd', 'f' }; 

into a std::string.

Is there any way to do it without iterating over the unsigned char array?

Thank you all.

like image 563
karlphillip Avatar asked Jan 14 '11 13:01

karlphillip


People also ask

Is std :: string guaranteed to be null-terminated?

Actually, as of C++11 std::string is guaranteed to be null terminated. Specifically, s[s. size()] will always be '\0' .

What happens if you don't null terminate a string?

Many library functions accept a string or wide string argument with the constraint that the string they receive is properly null-terminated. Passing a character sequence or wide character sequence that is not null-terminated to such a function can result in accessing memory that is outside the bounds of the object.

Do char arrays need to be null-terminated?

// Pre: char array must have null character at the end of data. Thus, we first find out how long the data is. The variable length will be the index of the first null character in the array, which is also the length of the data.


1 Answers

std::string has a constructor that takes a pair of iterators and unsigned char can be converted (in an implementation defined manner) to char so this works. There is no need for a reinterpret_cast.

unsigned char u_array[4] = { 'a', 's', 'd', 'f' };  #include <string> #include <iostream> #include <ostream>  int main() {     std::string str( u_array, u_array + sizeof u_array / sizeof u_array[0] );     std::cout << str << std::endl;     return 0; } 

Of course an "array size" template function is more robust than the sizeof calculation.

like image 128
CB Bailey Avatar answered Sep 21 '22 17:09

CB Bailey