Search code examples
c++pointersarduinoc-strings

string to char* function


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

Solution

  • This function :

    char* string2char(String command){
        if (command.length() != 0) {
            char *p = const_cast<char*>(command.c_str());
            return p;
        }
    }
    

    Does not make much sense, it takes string by value and returns pointer to its internal buffer, with cased away constnes(don't do it). You are getting some odd behaviour as you are returning values of object that already was destroyed, pass it by ref. Also I'm curious why you need to do all this stuff, can't you just pass:

    Serial.println(string1.c_str());
    Serial.println(string2.c_str());