String(big S) returns garbage

Ubuntu
Arduino IDE
ESP32

I originally posted this topic under "Can't return a String" and eventually marked it as solved by me. But I was wrong. I don't know how to update that post and I have changed my approach to the problem.

Simple, simple, simple... All I want to do is convert a char[] to a String (big S). There is a String constructor that takes a char[] and returns a String. But I always get garbage.

Here is the simplest program that demonstrates the problem.

Thank you for your help.

Here is the output:

MAC2STR(): '09:B8:15:D8:D8:1C'

MAC2STR: '09:B8:15:D8:D8:1C'
WHY GARBAGE?: '8⸮⸮?' <-- GARBAGE

And here is the entire sketch.

void MacToStr(unsigned char *mac, char *retBuf)
{
  snprintf(retBuf, 18, "%02X:%02X:%02X:%02X:%02X:%02X",
    mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

  printf("MAC2STR(): '%s'\n\n", retBuf);
}

void setup() 
{  
  // put your setup code here, to run once:
  Serial.begin(115200);
  
  unsigned char buf[6] = {0x09, 0xb8, 0x15, 0xd8, 0xd8, 0x1c};
  char strBuf[18];
  
  MacToStr(buf, strBuf);
       
  printf("MAC2STR: '%s'\n", strBuf);
  String myStr = String(strBuf);
  printf("WHY GARBAGE?: '%s'\n", myStr);
}

void loop() {
  // put your main code here, to run repeatedly:

}

Hello

printf expects a char pointer, but you give it a String object.

You can solve your problem with printf("WHY GARBAGE?: '%s'\n", myStr.c_str() );

But why use String ?

Well, that works! I never suspected printf!

Why String? Just trying different stuff.

Thank you guix!

Because you told printf() to expect a "char *" but passed instead a String.

Try:
printf("WHY GARBAGE?: '%s'\n", myStr.c_str());

I think there is a print() format for String but I can't remember what it is.

Your solution is correct as well. Thank you!

Arduino's print() function is "overloaded" and supports outputting Strings without any trouble, but printf() is just a C function without that capability, so the argument types have to exactly match the format specifiers (eg "%s" requires a "char *"), and it doesn't have a format specifier for C++ objects like "String"

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