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?
-
Because new Arduino users don't want to branch outTheDoctor– TheDoctor2014年03月01日 02:11:13 +00:00Commented Mar 1, 2014 at 2:11
-
Re "that method is not mentioned in the official Arduino documentation": It is available now: c_str()Peter Mortensen– Peter Mortensen2023年02月06日 03:33:22 +00:00Commented Feb 6, 2023 at 3:33
1 Answer 1
It seems like
c_str()
should be the preferred approach. Is there some reason whytoCharArray()
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.