Mehod String::toCharArray()

Post here first, or if you can't find a relevant section!
Post Reply
Phono
Posts: 68
Joined: Thu Mar 19, 2020 9:32 am

Mehod String::toCharArray()

Post by Phono »

I got surprised with the behaviour of this method.
I had a string object of length 20. I mean, 20 characters plus the terminal null.
After executing the statement
S.toCharArray(buf, 20)
I ended with a buffer containing the first 19 characters of my string, plus the terminating null.
I acknowledge that the reference document of Arduino.cc says:
===========================
string.toCharArray(buf, len)
Parameters
string: a variable of type String
buf: the buffer to copy the characters into (char [])
len: the size of the buffer (unsigned int)
===========================

So if len is 20, this can mean that the total length of the buffer is 20, including the terminating null. At the least, this is a bit misleading.
stevestrong
Posts: 502
Joined: Fri Dec 27, 2019 4:53 pm
Answers: 8
Location: Munich, Germany
Contact:

Re: Mehod String::toCharArray()

Post by stevestrong »

Be aware of the difference between strlen() and sizeof(), see https://www.geeksforgeeks.org/differenc ... -reviewed/.

Your string length is 20, but the size of the buffer to store those characters is 21.
So you need 21 bytes of any array to store the complete string, including the ending 0 byte.
As you only passed a 20 byte long array, the original string is capped and the last position is overwritten with 0.
I do not think that this is really "unexpected".
User avatar
fpiSTM
Posts: 1738
Joined: Wed Dec 11, 2019 7:11 pm
Answers: 91
Location: Le Mans
Contact:

Re: Mehod String::toCharArray()

Post by fpiSTM »

In fact the "len" is the length of the buffer parameters you gave. So it seems fine.
If your String S is: "Test". Calling S.toCharArray(buf, 20) you will have "Test\0" in buf.
If your String object has a length of 20 then you have to pass a buffer[21].
As mentioned in the String API for length:
https://www.arduino.cc/reference/en/lan ... ns/length/
Returns the length of the String, in characters. (Note that this doesn’t include a trailing null character.)
Maybe what is missing in the toCharArray() description is that the trailing null character is added to the buffer in any case.

String is a standard class from Arduino and toCharArray():
https://github.com/arduino/ArduinoCore- ... #L190-L191
relies on String::getBytes:
https://github.com/arduino/ArduinoCore- ... #L551-L562
mrburnette
Posts: 633
Joined: Thu Dec 19, 2019 1:23 am
Answers: 7

Re: Mehod String::toCharArray()

Post by mrburnette »

Phono wrote: Wed Feb 10, 2021 2:12 pm ...
So if len is 20, this can mean that the total length of the buffer is 20, including the terminating null. At the least, this is a bit misleading.
Nope. 'tis has always been this way. The string definition is:

Strings are actually one-dimensional array of characters terminated by a null character '\0'.
Post Reply

Return to “General discussion”