简体   繁体   中英

Problems returning const char* from function

First, thanks for taking some time helping me.

I am working on Arduino, and the thing is that I need to return a const char* on a function.

What I need to do is to create a String and send the response back. Things like this are not working:

...
String myVar= "Return Message";
return RPC_Response(myVar);
}

This didn't work, the String seems to be erased. Since I just get a blank response:

...
    const char* ch = new char;
    String myVar= "Return Message";
    ch = myVar.c_str();
    
    return RPC_Response(ch); 
}

But it only works If I do something like this: (But I need to create a String dynamically...)

. .

char *msg1 = "Return Message";
return RPC_Response(chmsg1); 
}

Or something like this:

. .

return RPC_Response("Return Message"); 
}

I have tried almost everything but nothing works...

Please...? Any idea of what Can I do???

First of all, you could simplify your code to the following:

    std::string myVar= "Return Message";
    return RPC_Response(myVar.c_str()); 

This will not work though, because the result of c_str() gets invalidated when a string gets modified, including the string being destroyed.

The reason using a string literal works is because string literals are stored globally. (It's actually implementation defined, but typically it is done so)

// storing it in a char* variable first is equivalent
return RPC_Response("Return Message");

Assuming RPC_Response only accepts C-strings, you would have do to this:

#include <string.h>
...

std::string myVar = "Return Message";
char* str = strdup(myVar.c_str());
return RPC_Response(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM