I have a function in a third-party library written in C: char* fix_filename_slashes(char* path). This function expects a mutable C-string passed to it so it can change all the slashes in the path to the correct use based on the operating system. All the strings I’m using in my Facade are declared as std::strings. I attempted to simply use foo.c_str() as every other function that expects a C string doesn’t change it and expects a const char *, but this function causes an error: Error: Argument of type "const char *" is incompatible with parameter of type "char *"
Is the result I came up with:
char* tempf = const_cast<char*>(filename.c_str());
filename = std::string(fix_filename_slashes(tempf));
tempf = NULL;
considered “correct” or are there other (more correct?) ways to accomplish the task?
EDIT
Whups. Apparently the function returns a COPY of the string. Still there are some nice answers already given.
If the string length does not change, you can use a pointer to the first character of the string. This is undefined behavior in the C++03 standard, but all known implementations work properly and it is explicitly allowed under the C++11 standard.
If the size of the string may change, you’ll have to do a little more work.