Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize std::string with char* containing null values

Tags:

c++

arrays

string

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?

like image 218
M.C. Avatar asked Jun 08 '26 01:06

M.C.


1 Answers

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.

like image 137
Jonathan Wakely Avatar answered Jun 10 '26 05:06

Jonathan Wakely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!