2

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?

2
  • 4
    Why are you calling c_str()? Commented Mar 13, 2016 at 17:41
  • 1
    Use the two-parameter constructor which takes an explicit size. Also, is there any reason why you have to use a std::string for this? Sounds like std::vector might be more suitable, in a way. Commented Mar 13, 2016 at 17:41

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.