Which is the better way to 'null' a char buffer?

Which is the better way to 'null' a char buffer?

These all produce the same result, for example strlen(buffer) is always zero. So what is the recommended way to null a character array? I am not sure about the last one because it caused me a problem in my project- the reason for my asking.

If I were still using String class, I would just say myString="";
But, I will not go back to using the String class.

Here is my test sketch:

/*
   buffer_tests
*/
char buffer[5];

//-------------------- setup() --------------------
void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();

  strcpy(buffer, "abcd");
  showBuffer();

  memset(buffer, 0, sizeof(buffer));
  showBuffer();

  strcpy(buffer, "abcd");
  buffer[0] = '\0';
  showBuffer();

  strcpy(buffer, "abcd");
  buffer[0] = {0};
  showBuffer();

  strcpy(buffer, "abcd");
  buffer[0] = 0;
  showBuffer();

}


void showBuffer() {
  Serial.print(F("buffer= '"));
  Serial.print(buffer);
  Serial.println(F("'"));
  Serial.print(F("strlen(buffer)= "));
  Serial.println(strlen(buffer));
  Serial.println();
}
//-------------------- loop() --------------------
void loop() {
}

"KISS Principle":

buffer[0] = '\0';
char myBuffer[6];

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

void loop()
{
  byte n = Serial.available();
  if (n == 5 )
  {
    for (int i = 0; i < 5; i++)
    {
      myBuffer[i] = Serial.read();
    }
    myBuffer[5] = '\0';  //null character
    Serial.println(myBuffer); //shows: abcd or any other string as entered from InputBox of Serial Monitor
  }
}

or

char myBuffer[6] = "";     //will hold 5 characters and a null-byte

It depends what you want to achieve. memset clears the full buffer and later on when filling it you don't have to worry about appending a NUL character.

If you only clear the first element and later overwrite it, "abcd" might become "zbcd" if you don't clear the second element.

Although 0 and '\0' represent the same value, it's more clear that you intend to add the NUL character if you use the latter when working with character arrays. Same applies to e.g. converting the characters '0'..'9' to the numbers 0..9. Some people subtract 48 but it's a lot easier to read if one subtracts '0'.

Why do you need to null a char buffer ?

You will not be using it as a string until you have put something in it and that is the best time to ensure that the terminating '\0' is present. Either do it expressly if adding characters to the string one by one or let the str* functions do it automatically.