Nothng Written to Serial when using sprintf I'm using sprintf to use a format specifier myTemplate with some strings. The result will then be written to Serial. Although the sketch compiles fine, it does not write any thing to the serial, nothing is seen in the Serial monitor.

Is sprintf being used wrongly here?

char* result;
char* myTemplate;

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);
}

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";
    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");

}




When I try the follwing sketch and write something to the Serial monitor, I receive gibberish echoed back to me!  Why is this?

Sketch

char received;
char* message = "";

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

void loop() {

    // Echos back
    if(Serial.available() &gt; 0) {
        received = Serial.read();
        Serial.println(message);


        if(received == '\n') {
            message = "";
        }  else {
            message += received;
        }


    }
}
When you use sprintf(), you need to have some space allocated for it to write the result to. At the moment, you're just passing an uninitialised pointer (result), meaning the behaviour of sprintf() is undefined. It might appear to work under some circumstances, but not others (and even if it did seem to work, it could have some nasty side effects on other parts of your code).

The simplest approach is to allocate a static char buffer. You need to be sure it's big enough to contain all of the text you want it to store though (plus an extra null character at the end).

For example:

char* myTemplate = "";
char result[64] = {0};

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

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";

    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");
}


As a side note, it's usually a good idea to initialise your variables. This is especially true for pointers.