I am trying to return a C string from a function. The function is suppose to concatinate the 3 integers with commas and return the result as a char array however I'm getting garbage values. I'm assuming I'm not calling malloc correctly. Can someone advise on what's the problem?
using namespace std;
const char * createCommand(int p1, int p2, int p3){
stringstream sstm;
std::string comma = ",";
sstm << p1 << comma << p2 << comma << p3;
std::string str = sstm.str();
const char *cstr = (const char *)malloc( (str.length()+1) * sizeof (char));
cstr = str.c_str();
return cstr;
}
int main() {
const char *cstr2 = createCommand(1,0,250); //I want to return "1,0,250"
printf("char = %s\n",cstr2);
}