Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 390
Allen Avatar asked Feb 14 '26 03:02

Allen


2 Answers

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());
like image 73
Mateusz Wojtczak Avatar answered Feb 15 '26 18:02

Mateusz Wojtczak


As noted by Mark Ransom in the comments, when you pass the string by value, the string command is a local copy of the original string. Therefore you can't return a pointer to its c_str(), because that one points at the local copy, which will go out of scope when the function is done. So you get the same bug as described here: How to access a local variable from a different function using pointers?

A possible solution is to rewrite the function like this:

const char* string2char(const String& command){
  return command.c_str();
}

Now the string is passed by reference so that c_str() refers to the same string object as the one in the caller (string1). I also took the libery to fix const-correctness at the same time.

Please note that you cannot modify the string by the pointer returned by c_str()! So it is very important to keep this const.

like image 30
Lundin Avatar answered Feb 15 '26 17:02

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!