I've been searching for ways of emptying a char array in C/C++. I have come up with this code:
char testName[20];
for(int i = 0; i < sizeof(testName); ++i)
{
testName[i] = (char)0;
}
It has been working for a while now but when I try to strlen
the result is always two more than the typed in word. For instance I input the word dog
the output would be five. Why is that so? Is my char array not cleared?
Here is my code:
char testName[20];
void loop()
{
if(Serial.available())
{
Serial.println("Waiting for name...");
index = 0;
for(int i = 0; i < sizeof(testName); ++i)
{
testName[i] = (char)0;
}
while(Serial.available())
{
char character = Serial.read();
testName[index] = character;
index++;
}
Serial.print("Name received: ");
Serial.println(testName);
Serial.print("The sentence entered is ");
Serial.print(strlen(testName));
Serial.println(" long");
delay(1000);
}
delay(1000);
}
Screenshot of the output:
Output as text:
Name received: dog
The sentence entered is 5 characters long