Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Arduino's .toCharArray() method have a bug?

Suppose I have a string "AB", that I want to convert to a char[] array and print the two char array elements in HEX to the serial monitor. Should be quite simple. However, the second element always prints as 0.

String line = "AB";
Serial.println();
Serial.print(line);
Serial.println();
char myarray[2];
line.toCharArray(myarray,2);
Serial.print(myarray[0],HEX);
Serial.print(' ');
Serial.print(myarray[1],HEX);
Serial.print(' ');

The output I am getting is

AB
41 0
like image 227
Albert Avatar asked May 21 '26 04:05

Albert


1 Answers

toCharArray will copy as many characters into the buffer as it can while still returning a valid C string. A valid C string has a nul (00) terminating byte. If you give it a 2 byte buffer, it can fit only one character before the nul terminator.

(Look at the Arduino source where it calculates how many characters to copy. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WString.cpp#L544 The bufsize - 1 is where it is leaving room for a nul terminator.)

Your code should be char myarray[3]; // Make room for 2 chars + nul terminator line.toCharArray(myarray, sizeof(myarray)); // Use sizeof to avoid repeating '2'

But really, you don't need a buffer to copy into at all. String already has a character accessor, charAt() Serial.print(line.charAt(0), HEX); Serial.print(line.charAt(1), HEX);

like image 171
frankleonrose Avatar answered May 23 '26 01:05

frankleonrose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!