since you use a String (not the best idea), why do you feel the need to go back to the char buffer (cString)... Go all the way and use the == operator directly on your string
== on cString will compare pointers... so that won't work in the general case. Here the compiler likely saw you have twice the same cString so only allocated one and thus pointers are equal.
You want to compare what is pointed to (each character until the end of the text, which is noted by a NULL '\0' char)... You need to use strcmp()
also - you are not a newbie anymore, read the forum rules and Please correct your post above and add code tags around your code:
[code]
[color=blue]// your code is here[/color]
[/code]
.
It should look like this:
// your code is here
(Also press ctrl-T (PC) or cmd-T (Mac) in the IDE before copying to indent your code properly)
The first sketch works by accident If you use normal strings (aka char arrays) you can't compare them with a simple ==. The pointers to the arrays get compared. But here you are tricked by the compiler. It sees you using "hello" two times so it uses the same memory for it. So when you do the compare both 'payload' and "hello" point to the same memory. In the second version that's not the case. Now you really have two different pointers.
If you want to do real string compare use for example strcmp().
And yeah, better not to start with a String in the first place.
So I don't see the difference between the two scripts.
My view
char *text = "123";
tells the compiler that there is "123" somewhere in memory (let's say at location 0x1234) and that text is a variable that points to that "123"; so the text variable contains 0x1234.
if ( text == "123")
tells the compiler / linker that there is "123" somewhere in memory; the compiler / linker knows that "123" was already somewhere in memory and will not create a new "123" but will use "123" at address 0x1234. And hence the result evaluates to true.
The below code shows where the c_str and the "123" are located in memory. Please note that String (capital C) objects allocate memory for their internal storage, so when you assign "123" to payload_2, it makes a copy.
String payload_2 = "123";
char *text = "123";
// print buffer
char buf[64];
void setup()
{
Serial.begin(57600);
sprintf(buf, "c_str located at %p", payload_2.c_str());
Serial.println(buf);
sprintf(buf, "text located at %p", text);
Serial.println(buf);
}
void loop()
{
}
NiekBeijloos:
Thank you very much I understand now!
that's what I tried to explain in #4 stating
== on cString will compare pointers... so that won't work in the general case. Here the compiler likely saw you have twice the same cString so only allocated one and thus pointers are equal.