am working with and Arduino nano and according to this, I can append strings to numbers by doing: stringThree = stringOne + 123;
but
when I do:
sensorValue = analogRead(A0);
String x1 = "{\"Volt\":"+sensorValue;
Serial.print(x1);
I get this unwanted output!
=gëÙrïË:_3ß»þTM1Æ3+Ç#ÿ1⁄4¿.Õ[Oû/g ̄>ïÿ1þ†lú0
but doing this it works fine.
sensorValue = analogRead(A0);
String x1 = "{\"Volt\":";
x1 += sensorValue;
Serial.print(x1);
"Volt":646
why?
1 Answer 1
In the first example you are adding an integer to the address of a string literal and then converting it to a String
.
In the second example you are converting a string literal to a String
and then appending an integer.
The key point here is string literal. The compiler just sees it as an address in flash memory. It's down to the functions you use with that address that define it as a string. So when you add an integer to it you are just adding an integer to the address, which of course changes the address. So then when you go to convert whatever is at that address to a String
you end up with garbage.
-
Pretty nice explanation... it must be maybe some kind of pointer operation behind the scenes...ΦXocę 웃 Пepeúpa ツ– ΦXocę 웃 Пepeúpa ツ2017年02月07日 12:10:44 +00:00Commented Feb 7, 2017 at 12:10
-
1That is precisely what it is. In C there is no such thing as a "string", only a pointer to some memory location. It's only when you use that pointer that the contents are interpreted as a "string".Majenko– Majenko2017年02月07日 12:11:35 +00:00Commented Feb 7, 2017 at 12:11
String
concatenation uses dynamic allocation, which can be problematic on small-memory devices. Anyhow, concatentation isn't needed for output -- see eg my answer to questions/33319 forStreaming
alternative, and my answer to questions/16122 for another example.