Issue with string termination character

Hello everybody, I've been searching a lot about strings today, but I couldn't find anything specific about this issue, so I decided to open a new topic.

I am reading a series of characters from Serial, and since I don't want to use the String data type I am trying to manually put the string termination character '\0' at the end of the string itself. The code works quite well, except that when the counter gets to 32 it automatically gets reset to 0. This has something to do with the string termination character, since if I comment out the line inString[counter] = '\0', the counter doesn't get reset anymore. Furthermore, if I change it to something like inString[counter] = '\1', the counter gets reset to 1 instead of 0.

Here is a basic version of the code:

int counter;
char inByte;
char inString[32];

void setup() {
  Serial.begin(9600);
}

void loop() {
  //counter = 0;

  if (Serial.available() > 0) {
    inByte = Serial.read();
    if (counter < 32 && inByte != '\n'){
      inString[counter] = inByte;
      counter++;
      inString[counter] = '\0';
    }
   Serial.print("inByte: ");
   Serial.println(inByte);

   Serial.print("inString: ");
   Serial.println(inString);

   Serial.print("counter: ");
   Serial.println(counter);
  }  
}

Any help would be appreciated. Thank you very much.

inString is only 32 characters long, including the terminator.
make it longer, 80.

Think about it...when counter gets to 31 then you essentially do the following:

      inString[31] = inByte;
      inString[32] = '\0';

You are writing past the end of the inString array!

gcjr:
inString is only 32 characters long, including the terminator.
make it longer, 80.

Thank you for your answer.
So, if I want to have no more than 32 characters (including string termination), I should write:
if (counter < 31 && inByte != '\n')
Because the index of the first character is 0. Is this right?

Change:

    if (counter < 32 && inByte != '\n'){

to

    if (counter < 31 && inByte != '\n'){

When you get to the end of the string you will no longer write any more characters to it.

Thank you!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.