I'm having some issues dealing with strings in a small Arduino app. I wonder why this code works:
mqtt.setServer("192.168.1.42", port);
and this code doesn't:
IPAddress ip = MDNS.queryHost(...);
mqtt.setServer(ip.toString().c_str(), port);
Even when strcmp
returns 0 when I compare both:
strcmp(ip.toString().c_str(), "192.168.1.42"); // output = 0 => equality
I've also tried other alternatives, such as creating a char
array, with no luck:
String ipstr = ip.toString();
char ipchar[ipstr.length() + 1];
ipstr.toCharArray(ipchar, ipstr.length() + 1);
mqtt.setServer(ipchar, port);
All alternatives compile, but the mqtt connection is never established later on. I must be missing something obvious because it works when I hardcode the "192.168.1.42" string.
mqtt.setServer
do? Does it store a pointer reference or does it copy the input string to its own buffers? If you use a constant "192.168.1.42" then that string will be static. WHen you useip.toString().c_str()
, when theip
object is deallocated but.setServer()
still has a reference to thatchar*
, it's become invalid. Where is the library you're using?