Albert
Albert

Reputation: 131

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

Upvotes: 3

Views: 1909

Answers (1)

frankleonrose
frankleonrose

Reputation: 365

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);

Upvotes: 2

Related Questions