-2

Task: delete "\n" at the beginning of the array.

Example:

char s_msg[15] = "\nHello world!";

void setup()
{
  Serial.begin(115200);
  Serial.println("Load");
  // Search \n
  if(strstr(s_msg, "\n") != NULL) {
    Serial.println(s_msg);
    strlcpy(s_msg, &s_msg[1], sizeof(s_msg));
    Serial.println(s_msg);
  }
}

void loop() {}

Description: If the \ n character is present at the beginning of the message, then we copy the original character to the same character, but without \ n.

Question: is it ok to copy char to itself (s_msg is the destination buffer and the source string at the same time)

  • why are you asking? ... try it first, then post a question if it does not work as expected – jsotola Jan 11 at 8:16
  • The documentation of strlcpy() should tell you. You might also look into memmove() and memcpy(). – the busybee Jan 11 at 8:43
  • this functions are 50 years old. there are books an many Internet sites describing them – Juraj Jan 11 at 8:49
  • the other question is why do you need to delete the leafing character? – jsotola Jan 11 at 9:51
4

This manual page of strlcpy() is quite clear:

If the src and dst strings overlap, the behavior is undefined.

This means you should avoid it, even if it works on some tests. The advice you got of just trying is not good advice. Use memmove() instead.

Not the answer you're looking for? Browse other questions tagged or ask your own question.