Difference between const char array and char array

In a sketch I have defined a function to send a character string to a client from a server in Arduino:

void sendDataToClient( char *sbuf) {
  size_t len = strlen(sbuf) + 1;
  for (i = 0; i < MAXCLIENTS; i++) {
  if (serverClients[i] && serverClients[i].connected()) {
    serverClients[i].write(sbuf, len);
    delay(1);
  }
 }
}

Initially I have done the test using a constant char array, the function works OK

char bufferMSGtoClient[] = "Hello world!\r\0";
-
-
sendDataToClient(bufferMSGtoClient);

Now I want to change the constant for a variable:

char bufferMSGtoClient[30];
-
time_t t = RTC.get();
formatTime(timestamp, t);
Serial.println( timestamp );
sprintf(bufferMSGtoClient, "%s", timestamp);

sendDataToClient(bufferMSGtoClient);

And the function no longer works, the client no longer receives the correct data, can someone tell me where I made the mistake?

What data does the client receive? You show some mystery function called formatTime() that presumably populates timestamp, which is a mystery variable and then put that into your buffer. A much easier way of copying strings is to use the strcpy() function. What does that println() function tell you?

Your initial literal string will have 2 nil characters since you explicitly add one into that string.

Check out snippets r us.

It doesn't look like you terminate the string. Maybe

sprintf(bufferMSGtoClient, "%s\r\0", timestamp);

?

peterkwa, that was missing, thanks!!

wrsalasr:
peterkwa, that was missing, thanks!!

But using sprintf() will terminate the string so your send function must be broken as it requires 2 nul characters in a string to function properly which is odd.

blh64: But using sprintf() will terminate the string so your send function must be broken as it requires 2 nul characters in a string to function properly which is odd.

Actually it's worse that that, because the resulting string at bufferMSGtoClient will NOT have two nulls with either code.

sprintf expects a null terminated string, and stops copying characters when it reaches the first null. Any \ escapes in character strings are reduced to their ASCII equivalents by the compiler at compile time, NOT by sprintf.

Therefore the suggested solution...

sprintf(bufferMSGtoClient, "%s\r\0", timestamp);

Is no different in operation or output from...

sprintf(bufferMSGtoClient, "%s\r", timestamp);

The only difference is that the first one is passed a doubly null terminated string. sprintf stops at the first null encountered regardless.

So the problem must be elsewhere.