how to make a character pointer point to a string?
hi, i need to pass a string to a function that only accepts char pointer. would something like this work?
string s("hello, i eat bbq");
char *myCharPtr;
s.copy(myCharPtr, s.size());
sendData(myCharPtr);
Use std::string::c_str() to convert a string to a c-style string. Like -
Or you can just pass it directly to the function.
myFunc( str.c_str() );
std::string foo = "hiya";char* cstring = foo.c_str();
Or you can just pass it directly to the function.
myFunc( str.c_str() );
Yup, the c_str() member function is what you're looking for. Be careful about keeping this pointer around though. I don't know what will happen if you try to modify the string after called c_str() then read from the c string. Or if it copies to a seperate buffer, what happens if you call c_str(), then modify, and call c_str() again.
this is the error i got when using c_str
sendData' : cannot convert parameter 1 from 'const char *' to 'class SomeData *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
sendData' : cannot convert parameter 1 from 'const char *' to 'class SomeData *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
Quote:I don't know what will happen if you try to modify the string after called c_str() then read from the c string. Or if it copies to a seperate buffer, what happens if you call c_str(), then modify, and call c_str() again.
The char* returned from c_str() (or data for that matter) will reflect changes made to the string. That data is owned and maintained by the string though, so don't attempt to modify/free the data witht he pointer returned (will result in undefined behavior). But you can read from it fine, and expect it to stay "correct".
Quote:Original post by MushuSince it's a const pointer, you can't modify the data without using a cast to begin with, which should be a tip off that something is not right.
The char* returned from c_str() (or data for that matter) will reflect changes made to the string. That data is owned and maintained by the string though, so don't attempt to modify/free the data witht he pointer returned (will result in undefined behavior). But you can read from it fine, and expect it to stay "correct".
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement