string to char* and dynamic allocation???

Sorry for this noob question but I'm very uncertain what I'm doing here. I have this function to convert a std::string to char*

1
2
3
4
5
6
7
8
char* stringToCharArray(std::string *stringParam)
{
    int stringLength = stringParam->length();
    char *stringTemp = (char*)malloc(stringLength*8 + 1);
    memcpy(stringTemp, stringParam->c_str(), stringLength);
    stringTemp[stringLength] = '\0';
    return stringTemp;
}


Then I use it like that:

1
2
3
    std::string company;
    company = string("BRB");
    quote->symbol = stringToCharArray(&company);


So if I later want to change the value of "company" to something else:


1
2
    company = "TRT";
    quote->symbol = stringToCharArray(&company);


This code is obviously wrong. Should I "free" quote->symbol before each assignment?
What is the proper way to convert a string to char* pass the result to a variable and later reuse that variable as many times as needed?
Last edited on
Why do you think that you need to convert string to char*?
You shouldn't generally use malloc() in C++, usually you use new[]. Also, cor copying c-strings there is strcpy() rather than memcpy():
1
2
3
4
5
6
7
8
9
10
11
12
13
14

char* stringToCharArray(std::string *stringParam)
{
    int stringLength = stringParam->length();

    // char *stringTemp = (char*)malloc(stringLength*8 + 1);
    char *stringTemp = new char[stringParam->length() + 1];

    // memcpy(stringTemp, stringParam->c_str(), stringLength);
    // stringTemp[stringLength] = '\0';
    strcpy(stringTemp, stringParam->c_str());

    return stringTemp;
}


EDIT:

Oh and yes, you need to delete[] quote->symbol before re-assigning it.
Last edited on
1. Well, the compiler thinks it needs it. It's not me.

2. Thank you for the tips, Galik.
Addressing the first element of a std::string by reference will treat it as a char*. So
1
2
std::string MyWord = "MyWord";
&MyWord[0]; //Treates The String As A char* 
Why do any of that?
myString.c_str(); //get const char*

But really... what do you need it for?
I am trying to use gSoap and it needs that.
+1 @ hanst. Just use the c_str function.
OK. But is it safe to assign const char* to char*? I've read that it is not.
ah, you're right, it's not. Well it depends.

It's actually hard to say whether or not it would be appropriate here without knowing what you're doing. What gSoap is doing with this string would determine a lot of what you'd need to do here.
Topic archived. No new replies allowed.