This post will discuss how to convert a std::string to const char* in C++. The returned pointer should point to a char array containing the same sequence of characters as present in the string object and an additional null terminator (‘\0’ character) at the end.

1. Using string::c_str function

We can easily get a const char* from the std::string in constant time with the help of the string::c_str function. The returned pointer is backed by the internal array used by the string object, and if the string object is modified, the returned pointer will also be invalidated.

Download  Run Code

Output:

std::string to const char*

2. Using string::data function

We can also call the string::data function on a std::string object to get const char*. This function works exactly like the string::c_str.

Download  Run Code

Output:

std::string to const char*

3. Using contiguous storage of C++11

We know that C++11 guarantees std::string‘s memory allocation to be contiguous. So, we can get a pointer to the underlying char[] array behind std::string by invoking &str[0] or &*str.begin(). This approach will not work with C++98/03 standard.

Download  Run Code

Output:

std::string to const char*

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