-
from const char to char
Hi All
I'm writing a tool that uses C libraries.
Which means that I have to convert strings into 'const char*'s
So, this is how I think a string is converted into a char:
Code:
const char* c = x.c_str ;
The problem I have now is that my C library functions need a char* not a const char*..
Any suggestions what the best way is to go from a string to a char* ?
Thanks a lot
LuCa
-
You should copy over the characters (anyway).
-
strcpy() will make a copy that you can alter.
-
If the size of the string is variable, you will probably need a variable length character array. In that case, use a vector so that it will handle memory management for you. Then pass the vector to the code that expects a char*:
Code:
string s = "Some string.";
vector<char> buf(s.begin(), s.end());
buf += '\0';
SomeCFunction(&buf[0], s.size()); // SomeCFunction takes a char* and an int size.
That code isn't tested, but should be basically correct.
(See 7stud's post below for corrections.)
-
Nice. I was trying to figure out how to handle the problem of variable lengths. Here's a tested version of Daved's solution:
Code:
void someCFunction(char* str)
{
cout<<str<<endl;
}
int main ()
{
string s = "Some string.";
vector<char> buf(s.begin(), s.end());
buf.push_back('\0');
someCFunction(&buf[0]);
return 0;
}
-
thanks a lot, this is all I need!!
The vector seems perfect!
LuCa
-
I guess this would be a better test:
Code:
void changeIt(char* str)
{
str[0] = 'X';
}
int main ()
{
string s = "Some string.";
vector<char> buf(s.begin(), s.end());
buf.push_back('\0');
changeIt(&buf[0]);
cout<<&buf[0]<<endl;
return 0;
}