Its supposed to convert a string to a char pointer. Apart from deleting after returning what is wrong with it? (And how can I delete a variable beforehand, if thats the variable I'm going to return? )
I tried this:
1 2 3 4 5 6 7 8
char * str(string s2c)
{
char * rv = new (nothrow) char (s2c.size());
for (int i = 0; i < s2c.size(); ++i)
rv[i] = s2c[i];
return rv;
delete [] rv;
}
char * str(string s2c)
{
char * rv = new (nothrow) char (s2c.size()); // should be [], as Luc Lieber mentioned
rv = s2c;
return rv; // the function EXITS when it returns
delete [] rv; // therefore this never happens
}
Note that there is no need for this function. If you need a char pointer from a string, just call string's c_str function, as Luc Lieber suggested.
@ Luc Lieber:
Const correctness!!!!
1 2 3 4
char* str(const std::string& s)
{
return s.c_str(); // will fail because c_str returns const char*, not char*
}
where, and how would I delete the local variable rv though?
btw I tried that... and it seems to working now... one othe problem i got to straighten out yet now is there is some extra garbage being appended to the end of the char * variable I am assigning to.
1 2 3 4
char * test;
string s = "Suck my dick!";
test = str (s);
cout << test << endl;
for example is giving me something like this:
Suck my dick!' ²/"j
Although to be fair it could be, and probably is the result of another part of my program heheh.
where, and how would I delete the local variable rv though?
You'd have to delete it from the calling function. This is passing ownership, and should be avoided when possible. It's one of the reasons why doing this is a bad idea.
Proper use would be:
1 2 3 4
string s = "whatever";
char* p = str(s);
cout << p;
delete[] p; // delete it here.
Although another problem with your function is that you need to put the null terminator at the end of the string, so it has its ending marked:
1 2 3 4 5 6 7 8
char * str(string s2c)
{
char * rv = new (nothrow) char [s2c.size() + 1]; // need to add 1 more for the null
for (int i = 0; i < s2c.size(); ++i)
rv[i] = s2c[i];
rv[i] = 0; // put the null at the end
return rv;
}