In C++, std::string::c_str() returns a const char* to a null-terminated version of the string\'s text.
Use it when a C library function needs a const char*. Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Call with empty brackets and pass the pointer to C APIs.
C++
const char* p = s.c_str();
std::puts(s.c_str());
Call
What it does
s.c_str()
Returns const char* to a null-terminated array owned by the string.
Do not modify through c_str(). Do not free it. Prefer keeping the std::string alive while the pointer is used.
Library declarations
C++
const char* c_str() const noexcept;
Parameters
Parameter
Description
None
c_str() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
const char*
Pointer to a null-terminated character sequence.
C++ Examples
Example 1 — Basic c_str()
Print using a C function.
C++
#include <cstdio>
#include <string>
int main() {
std::string s = "Hello C++";
std::puts(s.c_str());
return 0;
}