Go Down

Topic: Completely puzzled by toCharArray() (Read 11662 times) previous topic - next topic

askduino

Nov 16, 2013, 05:29 pm Last Edit: Nov 16, 2013, 05:32 pm by askduino Reason: 1
Code: [Select]
void setup() {
Serial.begin(9600);
 
 String input = "s421";

 char pinArray[2];
 input.substring(1,3).toCharArray(pinArray, 3);  
 
 char stateArray[1];
 input.substring(3,4).toCharArray(stateArray, 2);  

 int x = atoi(pinArray);
 int y = atoi(stateArray);

 Serial.println(x);
 Serial.println(y);

}


When I try to print the values of both charArrays together, one of the values will be wrong. However, when I remove either one of the .toCharArray conversion statements, the other value will start showing correctly. The correct values for x should be 42 and y is 1. Can someone please tell me what is going on? Thank you.

PaulS

Code: [Select]
  char pinArray[2];
  input.substring(1,3).toCharArray(pinArray, 3); 

How do you propose to store 3 elements in a 2 element array?

Code: [Select]
  char stateArray[1];
  input.substring(3,4).toCharArray(stateArray, 2); 

How do you propose to store 2 elements in a 1 element array?
The art of getting good answers lies in asking good questions.

askduino

Thanks PaulS, I changed the array size and it worked. Because I wanted to store 2 digits(2 elements), and 1 digit(1 element), so I declared 2 and 1 array respectively. That was what I don't quite understand why it needed a 3 element array. For the reason I stated the len 3 for the toCharArray argument is due to trial and error, because I originally entered 2 as well (2 digits), but I only got 1 character. Thanks anyhow.

PaulS

Two characters and a NULL require 3 elements in the array. The second argument is the size of the array. The toCharArray() function knows that it will be adding the NULL, so it only populates the array with n-1 characters, when you pass n as the size.
The art of getting good answers lies in asking good questions.

askduino

Right, I totally didn't know it will add a NULL. I just googled what you said and right, NULL termination. Really appreciate your enlightenment!

Go Up