Hi all! Newbie here.
Quite new to c / c++. I have a question about the below code:
char* string2char(String command){
if (command.length() != 0) {
char *p = const_cast<char*>(command.c_str());
return p;
}
}
void setup() {}
void loop() {
String string1 = "Bob";
char *string1Char = string2char(string1);
String string2 = "Ross";
char *string2Char = string2char(string2);
Serial.println(string1Char);
Serial.println(string2Char);
}
This basically outputs repeatedly:
Ross
Ross
I understand I'm failing to grasp the concept of how pointers are working here - would someone be able to explain it? And how would I alter this so that it could show:
Bob
Ross
p goes out of scope when the function ends. Anything you do with it after it goes out of scope you do at your own peril.
String's c_str() function returns a pointer to the String's internal buffer. It doesn't make a copy.
What's happening here is that you're passing each String to string2char by copy to its "command" parameter (which is a local variable to string2char), and the lifetime of "command" ends when string2char returns. Any pointer into that object is invalid after that point.
One simple change should fix that:
char* string2char(String& command){
There's another bug, though: What if the command String is empty? string2char doesn't return a value in that case. You need to return a valid pointer (even NULL would be fine, if that's your intention) in all cases.
This basically outputs repeatedly:
Without a Serial.begin() I bet it doesn't
Please explain what you are trying to do