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?