This post will discuss how to convert a std::string to char* in C++. The returned array should contain the same sequence of characters as present in the string object, followed by a terminating null character (‘\0’) at the end.

1. Using const_cast Operator

We know that both string::c_str or string::data functions returns const char*. To get a non-const version, we can use the const_cast operator, which removes the const attribute from a class. This works in constant time as no copying is involved.

Please note that this approach will give us direct access to the underlying data structure (i.e., an array) behind std::string. That means any change to the char* will be reflected in the string object and vice versa.

Download  Run Code

Output:

std::string to char*

2. Using strcpy() function

Here, the idea is to pass the const char* returned by the string::c_str or string::data functions to the strcpy() function, which internally copies it into the specified character array and returns a pointer it.

Download  Run Code

Output:

std::string to char*

3. Using std::copy function

Using C‘s strcpy() function is not the C++-style. The recommended approach is to use the standard algorithm std::copy instead, as shown below:

Download  Run Code

Output:

std::string to char*

4. Using std::vector function

We know that memory allocation of std::string is not guaranteed to be contiguous under the C++98/03 standard. The idea is to convert the string to a vector of chars whose memory allocation is contiguous. Then we can get a pointer to the underlying character array by invoking &str[0] or &*str.begin(). This approach is demonstrated below:

Download  Run Code

Output:

std::string to char*

5. C++11 – Contiguous storage of std::string function

Unlike C++98/03 standard, C++11 guarantees memory allocation of std::string to be contiguous. So, we can get a pointer to the underlying array behind std::string by invoking either the &str[0] or &*str.begin() function.

This works in constant time as no copying is involved. Please note that any change made to the char* will now be reflected in the string object and vice versa.

Download  Run Code

Output:

std::string to char*

That’s all about converting a std::string to char in C++.