Go Down

Topic: Bug : String concatenation garbage output. (Read 1 time) previous topic - next topic

LolrusPL

Test Envrionment :
Windows 7 x64 Arduino Mega
Ubuntu 9.10 Arduino Mega

Test Code
Code: [Select]
void setup()
{
Serial.begin(9600);
delay(1000);
Serial.println("Should print fine.");
int tmp = 13;
Serial.println("Printing 13 " + tmp);
Serial.println("Printed.");
}
void loop()
{
 
}
}


The output for "printing 13" does not arrive at all and the text "Printed." comes back twice.


westfw

"+" does not perform string concatenation, or conversion of integers to strings, in the arduino Language(s) (C, C++)

qistoph

LolrusPL, if you're looking for a way to correct your code, have a look at this:

Code: [Select]
   int tmp = 13;
   char str[12 + 2 + 1]; // 12 for string, 2 for tmp, 1 for \0
   snprintf(str, sizeof(str), "Printing 13 %d", tmp);
   Serial.println(str);

Groove

Quote
and the text "Printed." comes back twice.


The compiler probably put the strings, "Printing 13 " and "Printed." in consecutive locations in memory.
The first string occupies 13 bytes of memory (including the terminating null character)
Adding 13 to the address of the first string gives you the address of the second.

That's why "Printed." got printed twice.

HTH
Per Arduino ad Astra

Go Up