Call s.c_str(): it returns a const char* to the string's own buffer, ending in '\0', with no copy. For a writable char* use s.data() on a non-const string (C++17). Going the other way, std::string s = p; copies a C string, and std::string s(p, n); copies n bytes. The pointer is only valid while the string lives and is not changed.
C APIs (printf, fopen, strtok, most operating-system and library calls) speak char*, while C++ code holds std::string. A std::string already keeps its text in a '\0'-terminated array, so the conversion is just asking for a pointer to it. The questions are which pointer (read-only or writable), how long it stays valid, and what happens with text that is not terminated or has a '\0' inside. The sections below cover c_str(), writable pointers and copies, char* back to std::string, lifetimes, std::string_view and embedded nulls, and building an argv-style array, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1std::string to const char* with c_str()Recommended
c_str() is the answer for any function that only reads the text. It costs nothing: it returns a pointer to the characters the string already holds, followed by a '\0'. Since C++11, data() returns the same terminated buffer, so on a const string the two are interchangeable; c_str() says "I need a C string" more clearly. Convert at the call site, as in greet(name.c_str()), rather than storing the pointer.
#include <cstdio> #include <cstring> #include <iostream> #include <string> // A C-style function: it only reads the text, so it takes const char* void greet(const char* name) { std::printf("hello, %s\n", name); } int main() { std::string name = "Ada Lovelace"; // c_str() returns a const char* to the string's own buffer, // with a '\0' after the last character const char* p = name.c_str(); greet(p); greet(name.c_str()); // the usual form: convert at the call std::cout << "size: " << name.size() << ", strlen: " << std::strlen(p) << '\n'; std::cout << std::boolalpha << "terminator: " << (p[name.size()] == '\0') << '\n'; // data() returns the same pointer, also '\0'-terminated since C++11 std::cout << "same pointer: " << (name.data() == p) << '\n'; // No copy is made: the pointer sees the string's current text name[0] = 'a'; greet(p); // C functions that take a file name or a format want const char* std::string file = "notes.txt"; if (std::FILE* f = std::fopen(file.c_str(), "w")) { std::fputs("written through c_str()\n", f); std::fclose(f); std::cout << "wrote " << file << '\n'; } }
Output
Both calls print hello, Ada Lovelace. size: 12, strlen: 12 and terminator: true show the buffer is a proper C string, and same pointer: true shows data() and c_str() point at the same place. Because no copy is made, the pointer saw the edit: hello, ada Lovelace. An edit in place like name[0] = 'a' keeps the pointer valid; anything that can change the size may not (section 4 shows why). The last line, wrote notes.txt, is the usual reason people need this: std::fopen and friends take const char*. For std::ifstream you don't: it takes a std::string directly (see reading a file line by line).
2A writable char*: data() and copies
c_str() is const on purpose. Since C++17, data() on a non-const string returns char*, and you may change the characters through it (before C++17, write &s[0]). The rules: write only inside [0, size()), never change the length behind the string's back, and leave the terminator alone. To let a C function fill a string, size it first and trim it after. When a function cuts its input apart (strtok) or the pointer must outlive the string, work on a copy: a std::vector<char> or a std::unique_ptr<char[]>, which free themselves.
#include <cstdio> #include <cstring> #include <iostream> #include <memory> #include <string> #include <vector> // C functions that write into the text take char*, not const char* void shout(char* text) { for (char* c = text; *c != '\0'; ++c) if (*c >= 'a' && *c <= 'z') *c = *c - 'a' + 'A'; } int main() { // 1. C++17: data() on a non-const string returns char* std::string s = "edit me"; char* p = s.data(); shout(p); std::cout << "data(): " << s << '\n'; // &s[0] is the pre-C++17 spelling of the same pointer std::string t = "old style"; shout(&t[0]); std::cout << "&s[0]: " << t << '\n'; // 2. A C function that fills a buffer: size the string first, // then trim it to the length the function reports std::string out(32, '\0'); int n = std::snprintf(out.data(), out.size() + 1, "%d items at %.2f", 3, 4.5); out.resize(n); std::cout << "snprintf: [" << out << "] size " << out.size() << '\n'; // 3. strtok cuts its input apart, so give it a copy, never c_str() std::string csv = "red,green,blue"; std::vector<char> buf(csv.c_str(), csv.c_str() + csv.size() + 1); for (char* tok = std::strtok(buf.data(), ","); tok != nullptr; tok = std::strtok(nullptr, ",")) std::cout << "token: " << tok << '\n'; std::cout << "csv unchanged: " << csv << '\n'; // 4. A char* that must outlive the string: copy into owned memory auto copy = std::make_unique<char[]>(csv.size() + 1); std::memcpy(copy.get(), csv.c_str(), csv.size() + 1); csv.clear(); std::cout << "copy: " << copy.get() << '\n'; }
Output
shout writes through the pointer, so the strings themselves change: data(): EDIT ME and &s[0]: OLD STYLE. The snprintf call got a 32-character buffer, reported 15 characters written, and resize(n) trimmed the zeros: snprintf: [3 items at 4.50] size 15. Passing size() + 1 is fine because the string always owns one more byte for the terminator, and snprintf only writes a '\0' there. (C++23 adds resize_and_overwrite for this pattern; this page compiles as C++20.) strtok wrote '\0's into the vector's copy, so csv unchanged: red,green,blue; for real splitting, see splitting a string. The unique_ptr<char[]> copy survives csv.clear(). Avoid const_cast<char*>(s.c_str()): it compiles, but if the function writes through it, the behaviour is undefined.
3char* to std::string
The other direction is a constructor. std::string s = p; copies characters up to the first '\0', so it works for const char*, char* and char arrays alike, and = and += accept a C string as well. When the bytes are not terminated (a network buffer, a record read from a file) or may contain '\0', pass the length: std::string(p, n), or an iterator pair. A null pointer is not an empty string: constructing from nullptr is undefined behaviour, so check first.
#include <cstddef> #include <cstring> #include <iostream> #include <string> #include <string_view> // Wrap a C string that may be null: std::string(nullptr) is undefined std::string to_string_or_empty(const char* p) { return p ? std::string(p) : std::string(); } int main() { // 1. A '\0'-terminated const char*: the constructor copies up to the '\0' const char* c = "from a C string"; std::string a = c; std::cout << a << " (" << a.size() << " chars)\n"; // Assignment and += take a const char* too std::string b; b = "assigned"; b += c + 4; // pointer arithmetic: skip "from" std::cout << b << '\n'; // 2. A char array filled by C code: same constructor char buf[32]; std::strcpy(buf, "from a char array"); std::string d = buf; std::cout << d << '\n'; // 3. Bytes with a known length (no '\0', or '\0' inside): pass the size const char raw[] = {'a', 'b', '\0', 'c', 'd'}; std::string cut = raw; // stops at the first '\0' std::string full(raw, sizeof raw); std::cout << "cut size " << cut.size() << ", full size " << full.size() << '\n'; std::string range(raw + 3, raw + 5); // or an iterator pair std::cout << "range: " << range << '\n'; // 4. A null pointer: check before converting const char* missing = nullptr; std::cout << "null gives [" << to_string_or_empty(missing) << "]\n"; // 5. No copy needed? A string_view looks at the C string in place std::string_view view = c; std::cout << "view: " << view.substr(7) << '\n'; }
Output
The constructor copied all 15 characters: from a C string (15 chars). c + 4 is still a const char*, so += appended the rest of the text after from (assigned a C string). With five bytes and a '\0' in the middle, the plain constructor stopped early while the length form kept everything: cut size 2, full size 5; the iterator pair took the last two bytes (range: cd). The helper turns a null pointer into null gives []. Without the check, GCC's library happens to throw std::logic_error with basic_string: construction from null is not valid, but other libraries just crash; C++23 also deletes the std::nullptr_t constructor so a literal nullptr no longer compiles. A std::string_view skips the copy when you only need to read (view: C string), as long as the C string outlives it.
4How long the pointer stays valid
The pointer from c_str() or data() belongs to the string. It becomes invalid when the string is destroyed, and may become invalid on any change that can grow or shrink it (+=, append, push_back, insert, resize, assignment). The classic bug is const char* p = f().c_str(); with a function that returns a std::string by value: the temporary dies at the semicolon and p points at freed memory. Using the temporary inside one expression is fine, because it lives until the end of that full expression.
#include <cstdint> #include <cstdio> #include <iostream> #include <string> std::string make_label(int id) { return "item-" + std::to_string(id); } // Returning c_str() of a local would dangle; return the string itself std::string label_for(int id) { return make_label(id); } int main() { // OK: the temporary lives until the end of the full expression, // so the pointer is valid for the whole call std::puts(make_label(1).c_str()); // WRONG (not run): the temporary dies at the semicolon // const char* bad = make_label(2).c_str(); // std::puts(bad); // undefined behaviour: reads freed memory // RIGHT: keep the string in a variable as long as the pointer std::string keep = make_label(2); const char* good = keep.c_str(); std::puts(good); // Changing the string can move its buffer. A short string lives // inside the object; growing it moves the text to the heap. std::string s = "short"; auto before = reinterpret_cast<std::uintptr_t>(s.c_str()); std::cout << "capacity " << s.capacity(); s += ", now long enough to need the heap"; auto after = reinterpret_cast<std::uintptr_t>(s.c_str()); std::cout << " -> " << s.capacity() << '\n'; std::cout << std::boolalpha << "buffer moved: " << (before != after) << '\n'; // Any pointer taken before the += is now dangling: call c_str() again std::puts(s.c_str()); std::puts(label_for(3).c_str()); }
Output
item-1 prints safely from the temporary inside the puts call, and item-2 from a pointer whose string is kept in a variable. The dangling version stays in a comment: reading freed memory is undefined behaviour, and its output (often the right text, sometimes garbage) proves nothing. The capacity line, capacity 15 -> 39, is GCC's small-string optimisation at work: up to 15 characters live inside the std::string object, and the append moved the text to a heap block, so buffer moved: true. Any pointer taken before the += is now dangling; call c_str() again after a change. A function should return the std::string (item-3), never c_str() of a local.
5string_view and embedded '\0' bytes
Two cases break the "text ends at '\0'" assumption that every C function makes. A std::string_view has data() but no c_str(), because its text often is a slice of something longer, with no terminator where the view ends. And a std::string can hold '\0' bytes in the middle: size() counts them, but a C function stops at the first one.
#include <cstdio> #include <cstring> #include <iostream> #include <string> #include <string_view> int main() { // A string_view has data() but no c_str(): its text need not end // in '\0'. Here the view is "hello", inside a longer literal. std::string_view word = std::string_view("hello world").substr(0, 5); std::printf("data(): [%s]\n", word.data()); // runs past the view // Fix 1: copy into a std::string, which is always '\0'-terminated std::printf("string: [%s]\n", std::string(word).c_str()); // Fix 2: pass the length to printf with %.*s std::printf("%%.*s: [%.*s]\n", static_cast<int>(word.size()), word.data()); // A std::string may hold '\0' bytes; C functions stop at the first one using namespace std::string_literals; std::string bytes = "key\0value"s; // the s suffix keeps the '\0' std::cout << "size: " << bytes.size() << ", strlen(c_str()): " << std::strlen(bytes.c_str()) << '\n'; std::printf("printf sees [%s]\n", bytes.c_str()); // C++ code uses size(), so it sees every byte (the '\0' shown as \0) std::cout << "loop sees ["; for (char ch : bytes) { if (ch == '\0') std::cout << "\\0"; else std::cout << ch; } std::cout << "]\n"; // Without the s suffix, the constructor stops at the '\0' too std::string plain = "key\0value"; std::cout << "plain size: " << plain.size() << '\n'; }
Output
The view is hello, but printf with its data() printed data(): [hello world]: it kept reading until the literal's own '\0'. With a view into something that has no terminator at all, it would read past the end, which is undefined. Copying into a std::string or passing the length with %.*s both print [hello]. The string built with the s suffix holds 9 bytes, yet strlen and printf see only key, while the loop over the string sees [key\0value]. Built from a plain literal, the constructor stops at the '\0' itself: plain size: 3. For binary data, pass data() and size() together, never c_str() alone.
6A vector of strings to char** (argv)
Some C APIs take an array of strings: execv, main-style argc/argv parsers, or a list of options. Keep the text in a std::vector<std::string> and build a second vector of pointers into it, with a nullptr at the end when the API expects one. Nothing is copied, so the strings must outlive the pointer array and must not change while it is in use.
#include <cstdio> #include <string> #include <vector> // A C-style API: a count plus an array of char*, like main's argv int c_main(int argc, char** argv) { for (int i = 0; i < argc; ++i) std::printf("argv[%d] = %s\n", i, argv[i]); return argv[argc] == nullptr ? 0 : 1; // exec-style arrays end in null } int main() { std::vector<std::string> args = {"tool", "--verbose", "input.txt"}; // One char* per string, pointing into the strings themselves. // args must outlive ptrs, and must not change while ptrs is used. std::vector<char*> ptrs; ptrs.reserve(args.size() + 1); for (std::string& a : args) ptrs.push_back(a.data()); ptrs.push_back(nullptr); int rc = c_main(static_cast<int>(args.size()), ptrs.data()); std::printf("returned %d\n", rc); // For an API that takes const char* const*, use c_str() instead std::vector<const char*> views; for (const std::string& a : args) views.push_back(a.c_str()); std::printf("%zu const pointers, last: %s\n", views.size(), views.back()); }
Output
c_main printed each argument from the char** and found the nullptr after the last one, so it prints returned 0. Use data() when the API is declared with char** (as execv is), and c_str() into a std::vector<const char*> when it takes const char* const*: 3 const pointers, last: input.txt. The reserve is not needed for correctness, since the pointers point into the strings, not into ptrs; what matters is that args is not resized or changed while ptrs is in use.
7Which should you use?
| Method | Gives you | Copies? | Use it for |
|---|---|---|---|
| s.c_str() | const char*, '\0'-terminated | No | Any C function that reads the text |
| s.data() | char* (C++17, non-const string) | No | C functions that edit or fill the buffer in place |
| std::vector<char>(s.c_str(), s.c_str() + s.size() + 1) | A separate writable char* | Yes | strtok and other functions that cut the text |
| std::make_unique<char[]>(n) + memcpy | An owned char* that outlives the string | Yes | Keeping a C string after the std::string is gone |
| std::string s = p; / std::string(p, n) | A std::string from a char* | Yes | Taking ownership of C text; use (p, n) for raw bytes |
| std::string_view(p) | A read-only view of a char* | No | Reading C text without copying it |
| const_cast<char*>(s.c_str()) | A char* you must not write through | No | Avoid: use data() instead |
Frequently asked questions
What is the difference between c_str() and data()?
Since C++11, none for reading: both return a pointer to the same buffer, followed by a '\0', and both are constant time with no copy (the example prints same pointer: true). Before C++11, data() did not promise a terminator. Since C++17, data() on a non-const string returns char*, which you may write through, while c_str() always returns const char*. Use c_str() to say "this goes to a C function" and data() when you need to write.
Why does char* p = s.c_str(); not compile?
c_str() returns const char*, and C++ does not drop const implicitly. GCC reports error: invalid conversion from 'const char*' to 'char*' [-fpermissive]. Declare the pointer as const char* if you only read, use s.data() (C++17) if you need to write into the string, or copy the text into a std::vector<char> if the function must not touch the original. Casting the const away with const_cast compiles but is undefined behaviour if anything writes through the pointer.
How do I copy a std::string into a char array?
Copy with a size limit and make sure the result ends in '\0'. std::snprintf(buf, sizeof buf, "%s", s.c_str()) does both in one call and truncates if the text is too long: with char buf[9] and "Ada Lovelace" it gives Ada Love. std::size_t n = s.copy(buf, sizeof buf - 1); buf[n] = '\0'; does the same without printf. Avoid strcpy, which overflows the array when the string is longer than it.
Is it safe to return s.c_str() from a function?
Only if s outlives the call, such as a member of an object that is still alive or a static string. Returning c_str() of a local variable or a temporary returns a pointer into memory that is freed when the function returns, which is undefined behaviour. Return the std::string by value instead; the move is cheap, and the caller calls c_str() where it needs the pointer.
How do I get a const char* from a std::string_view?
A std::string_view is not guaranteed to be '\0'-terminated, so sv.data() is not a C string. Make one with std::string(sv).c_str(), keeping the std::string alive while the pointer is used, or pass the length along, as in printf("%.*s", static_cast<int>(sv.size()), sv.data()). Passing sv.data() alone makes the C function read past the end of the view.
Do I need to free the pointer returned by c_str()?
No. The buffer belongs to the std::string, which frees it in its destructor; calling delete or free on it is a double free. You only free what you allocated yourself, and even that is best left to a std::vector<char> or std::unique_ptr<char[]> so it frees itself.