8

When reading/trying a recent answer, I was surprised to see that Arduino's String class supports the c_str() method, just like the C++ std::string class. As expected, it appears to get a pointer to the string's contents as a null-terminated char array (i.e. C-style string).

However, (as far as I can see) that method is not mentioned in the official Arduino documentation. Additionally, in all example code I've seen using String, a different approach seems to be used. A secondary char buffer is setup, and then the contents of the string are copied to it using String::toCharArray(). This obviously requires double the memory, plus an O(n) copy operation.

It seems like c_str() should be the preferred approach. Is there some reason why toCharArray() is more commonly used?

asked Feb 28, 2014 at 17:03
2
  • Because new Arduino users don't want to branch out Commented Mar 1, 2014 at 2:11
  • Re "that method is not mentioned in the official Arduino documentation": It is available now: c_str() Commented Feb 6, 2023 at 3:33

1 Answer 1

3

It seems like c_str() should be the preferred approach. Is there some reason why toCharArray() is more commonly used?

basically, I'd say it's a lack of knowledge from the people doing the codes you've seen. Definitely c_str() is better. Though, what I see even more often is the use of character arrays char* strings instead of String (and I plead guilty of that as well in my own codes).

And that's because the Arduino library has been built upon a messy set of C and C++ libraries and coding style. Trying to make things easier actually messed them up and complicated them more.

That's actually why we have new projects like xpcc trying to make a real and smart use of the C++ abilities in the embedded world.

answered Mar 1, 2014 at 13:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.