Reputation: 1745
I have a function that has the following signature
void serialize(const string& data)
I have an array of characters with possible null values
const char* serializedString
(so some characters have the value '\0'
)
I need to call the given function with the given string!
What I do to achieve that is as following:
string messageContents = string(serializedString);
serialize(messageContents.c_str());
The problem is the following. The string assigment ignores all characters occuring after the first '\0'
character.
Even If I call size()
on the array I get the number of elements before the first '\0'
.
P.S. I know the 'real' size of the char array (the whole size of the arrray containing the characters including '\0'
characters)
So how do I call the method correctly?
Upvotes: 2
Views: 3382
Reputation: 171253
Construct the string with the length so it doesn't only contain the characters up to the first '\0'
i.e.
string messageContents = string(serializedString, length);
or simply:
string messageContents(serializedString, length);
And stop calling c_str()
, serialize()
takes a string so pass it a string:
serialize(messageContents);
Otherwise you'll construct a new string from the const char*
, and that will only read up to the first '\0'
again.
Upvotes: 9