Completely puzzled by toCharArray()

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.

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

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

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

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

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.

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.

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!