C++

Fix C++ "cannot convert 'std::string' to 'const char*'" — c_str(), data(), and When the API Wants char*

A std::string is not a character pointer, and no implicit conversion turns one into the other. This guide takes the exact error at a std::fopen call, fixes the read-only case with c_str(), fixes the mutable case with data(), and separates the one pointer that is never null-terminated, a string_view's data(), from the two that are.

Written November 22, 2026 · Tested with GCC 13.3.0 · 12 min read

By the end of this guide
  • The first failure: a string passed to std::fopen
  • Reading the error
  • The second failure: cstr() passed to a char parameter
  • The fixed program: cstr() for readers, data() for writers

Written November 22, 2026

Tested with GCC 13.3.0

What this guide is

Every C library function, and a large share of older C++ APIs, takes text as a const char*: a pointer to a null-terminated array of characters. A std::string holds the same characters, but it is a class object that owns them, and the class provides no implicit conversion to a character pointer. Passing the string itself where a const char* is expected is therefore a compile error, not a conversion the compiler performs quietly. The bridge is explicit, and it is two member functions: c_str() and data(). Both return a pointer to the string's underlying character array, and since C++11 that array is null-terminated, with data()[i] == operator[](i) for every position in [0, size()] and a null character at data()[size()].

The two functions differ in one place, and that place decides which fix compiles. c_str() has only a const form: it returns const CharT*, always. data() has two forms. The const overload returns const CharT*. The non-const overload, present since C++17, returns CharT*, a writable pointer to the same null-terminated array. So the read-only API takes either function, while an API that wants char* takes only data() called on a non-const string, and only in C++17 or later. Writing through c_str(), or modifying the terminating null at data()[size()] to any value other than CharT(), is undefined behavior.

This guide works through the failures in the order they are usually met. The first program passes a string straight to std::fopen and earns the error in this guide's title. The second passes c_str() to a function taking char* and earns a different error, about const, not about the string. The fixed program then opens and writes a real file through c_str(), uppercases its own characters through data(), and checks the terminating null in place. Two shorter programs close the guide: one shows a saved pointer changing when the string grows, and one shows why a std::string_view's data() is not a substitute for either function.

Build every program in this guide with g++ -std=c++17. Nothing here needs a newer standard: the writable data() overload is a C++17 feature, and the null-termination guarantee is C++11.

The first failure: a string passed to std::fopen

std::fopen is the ordinary shape of the problem: a standard function whose first parameter is const char*, called with a path the program naturally holds in a std::string:

C++
#include <cstdio>
#include <string>

int main() {
    std::string path = "report.txt";
    std::FILE* f = std::fopen(path, "r");
    if (f) std::fclose(f);
    return 0;
}
Terminal
$ g++ -std=c++17 -g -Wall -Wextra -o fail_const fail_const.cpp
fail_const.cpp: In function 'int main()':
fail_const.cpp:6:31: error: cannot convert 'std::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'
    6 |     std::FILE* f = std::fopen(path, "r");
      |                               ^~~~
      |                               |
      |                               std::string {aka std::__cxx11::basic_string<char>}
In file included from /usr/include/c++/13/cstdio:42,
                 from fail_const.cpp:1:
/usr/include/stdio.h:264:44: note:   initializing argument 1 of 'FILE* fopen(const char*, const char*)'
  264 | extern FILE *fopen (const char *__restrict __filename,
      |                     ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~

Reading the error

Read the error in three parts. The first line names both types exactly: the argument is a std::string, spelled out as std::__cxx11::basic_string<char>, and the parameter wants const char*. There is no conversion between them for the compiler to apply, so the call is rejected as written. The caret block below it points at the argument itself, path, not at the function name: the call site is the defect, and std::fopen is blameless. The note at the end confirms which parameter failed by quoting the declaration, FILE* fopen(const char*, const char*), and marking argument 1. When the same error names a function from a library you use instead of fopen, the reading is identical: find the parameter type in the note, then give that parameter a pointer instead of the string.

Two fixes that look plausible do not work, and the error explains why. A cast, static_cast<const char*>(path), fails the same way, because a cast can only use a conversion that exists, and none does. Taking the address of the first character used to be the workaround before C++17, and &path[0] does give a char* on a non-const string, but it states the intent worse than data() and, on a const string, gives a const char* whose guarantees the reader has to reconstruct. The member functions exist so the call site says what it means: hand over the characters, read-only or writable.

The second failure: c_str() passed to a char* parameter

Fix the first error with c_str() and a second, different error appears as soon as the receiving function can write through its parameter. This function uppercases the text it is given, in place, so its parameter is char*, not const char*:

C++
#include <cstring>
#include <string>

void shout(char* text) {
    for (std::size_t i = 0; text[i] != '\0'; ++i)
        if (text[i] >= 'a' && text[i] <= 'z')
            text[i] = static_cast<char>(text[i] - 'a' + 'A');
}

int main() {
    std::string word = "hello";
    shout(word.c_str());
    return 0;
}
Terminal
$ g++ -std=c++17 -g -Wall -Wextra -o fail_mutable fail_mutable.cpp
fail_mutable.cpp: In function 'int main()':
fail_mutable.cpp:12:21: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
   12 |     shout(word.c_str());
      |           ~~~~~~~~~~^~
      |                     |
      |                     const char*
fail_mutable.cpp:4:18: note:   initializing argument 1 of 'void shout(char*)'
    4 | void shout(char* text) {
      |            ~~~~~~^~~~

This error is not about std::string at all. The conversion from the string to a pointer already happened: c_str() returned a const char*. What fails is the next step, dropping const, which no implicit conversion does either. c_str() is specified to return a non-modifiable array, and writing to the character array accessed through it is undefined behavior, so the type is the enforcement. The [-fpermissive] tag in the error is a trap of its own: compiling with -fpermissive would downgrade this error to a warning and let the call through, and the resulting program would write through a pointer the string never granted write access to. The correct fix is not a flag and not a const_cast. It is the other member function, called on a string that is not const.

The fixed program: c_str() for readers, data() for writers

Both fixes in one program, against a real file:

C++
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>

void shout(char* text) {
    for (std::size_t i = 0; text[i] != '\0'; ++i)
        if (text[i] >= 'a' && text[i] <= 'z')
            text[i] = static_cast<char>(text[i] - 'a' + 'A');
}

int main() {
    std::string path = "report.txt";
    std::FILE* f = std::fopen(path.c_str(), "w");
    if (!f) return 1;
    std::fputs("first line\n", f);
    std::fclose(f);
    std::cout << "wrote " << path << '\n';

    std::string word = "hello";
    shout(word.data());
    std::cout << "word = " << word << '\n';
    std::cout << "word.data()[5] is null: " << (word.data()[5] == '\0' ? "yes" : "no") << '\n';
    std::cout << "strlen(word.data()) = " << std::strlen(word.data()) << '\n';
    return 0;
}
Terminal
$ g++ -std=c++17 -g -Wall -Wextra -o fixed fixed.cpp
$ ./fixed
wrote report.txt
word = HELLO
word.data()[5] is null: yes
strlen(word.data()) = 5

The file report.txt now contains the single line first line. Three facts carry the program. First, path.c_str() satisfies std::fopen because the function only reads the path, and its parameter is const char*, which is exactly what c_str() returns. Second, word.data() satisfies shout(char*) because word is a non-const string, so the C++17 non-const overload is selected and returns char*; the uppercase writes land in the string's own storage, which is why printing word afterward shows HELLO. Third, the array behind both pointers is null-terminated: index 5 of a five-character string is the null character, and std::strlen, which knows nothing about std::string, measures the array at 5. That last check is the one to keep when an API is involved: any function that scans for a terminator, strlen, fopen, a C logger, is relying on the guarantee that data()[size()] is null, and for std::string that guarantee holds since C++11.

One boundary on the writable form: the characters in [data(), data() + size()) may be modified, but the terminating null at data()[size()] may only ever hold the value CharT(). A writer that overwrites the terminator, or that writes past it, has left the array the string owns, and the string's own later operations read a corrupted state. A char* API that appends, such as one built on strcat, is therefore not a fit for data() either: appending belongs on the string itself, with append or +=, after which a fresh pointer can be taken.

The lifetime rule: the pointer ends when the string changes

Neither function copies anything. The pointer names the string's own storage, and it stays valid only while that storage does. The documented invalidation rule is the same for c_str() and data(): the pointer may be invalidated by passing a non-const reference to the string to any standard library function, or by calling non-const member functions on the string, with a short list of exceptions that includes operator[], at(), front(), back(), and the iterator functions. In practice the common case is growth: an append, an insert, a +=, or an assignment that needs more room reallocates the array, and every pointer taken before it dangles.

C++
#include <iostream>
#include <string>

int main() {
    std::string s = "short";
    const char* before = s.c_str();
    s.append(1000, 'x');
    const char* after = s.c_str();
    std::cout << "pointer changed after append: " << (before != after ? "yes" : "no") << '\n';
    std::cout << "size = " << s.size() << '\n';
    return 0;
}
Terminal
$ g++ -std=c++17 -g -Wall -Wextra -o lifetime lifetime.cpp
$ ./lifetime
pointer changed after append: yes
size = 1005

The saved pointer changed because appending 1,000 characters forced a new, larger allocation, and the old array was released. Reading through before after the append would read freed or reused memory, the same defect class as any dangling pointer. The working rule is short: take the pointer at the call that uses it, pass it, and do not store it. A pointer held across any code that can modify the string, including code in another function that received the string by non-const reference, is a pointer held too long. Where a C API keeps the pointer after the call, and some registration and callback APIs do, the string itself has to outlive that use, owned by an object whose lifetime covers it, and the string must not be modified in between.

The string_view trap: data() with no terminator behind it

Trap
One nearby pointer looks interchangeable and is not. A std::string_view also has a data(), and it also returns a pointer to characters, but a view is a pointer and a length over somebody else's array, and that array is not necessarily null-terminated. The documentation says so directly: unlike std::basic_string::data() and string literals, a view's data() returns a pointer to a buffer that is not necessarily null-terminated, for example a substring view, and passing it to a routine that expects a null-terminated string is typically a mistake.
C++
#include <cstring>
#include <iostream>
#include <string>
#include <string_view>

int main() {
    std::string text = "hello world";
    std::string_view first = std::string_view(text).substr(0, 5);
    std::cout << "view size = " << first.size() << '\n';
    std::cout << "view = " << first << '\n';
    std::cout << "strlen(view.data()) = " << std::strlen(first.data()) << '\n';
    return 0;
}
Terminal
$ g++ -std=c++17 -g -Wall -Wextra -o viewtrap viewtrap.cpp
$ ./viewtrap
view size = 5
view = hello
strlen(view.data()) = 11

The view is five characters, and printing the view respects that length. std::strlen knows no length: it scans from first.data() until it finds a null, which is the terminator of the full string text, eleven characters in. Handed to std::fopen, the same pointer would open hello world, not hello. When the text arrives as a view and a C API needs a terminated string, the conversion goes through an owning string first: construct a std::string from the view, with std::string(first), and pass that string's c_str(). The copy is the price of the terminator, and it is the only correct route when the viewed array is a substring.

The fixes, ranked

Pass c_str() to a const char* parameter. This is the title error's fix and the most common case: file functions, C logging, std::atoi and its relatives, and any API that reads the text and returns. data() on a const string returns the same const char* and is equally correct; c_str() is ranked first here only because its name states the intent, a C string, at the call site.

Pass data() on a non-const string to a char* parameter, in C++17 or later. The non-const overload returns char* pointing at the same null-terminated array, and the characters in [data(), data() + size()) may be modified. The string must be non-const at the call: on a const string the const overload is selected, the return is const char*, and the original const error returns. Before C++17 this overload does not exist, which is the one case where &s[0] on a non-const string is the historical route.

Never force the const case. No -fpermissive, no const_cast around c_str(). The const in the return type is the string's statement that the array is read-only, and writing through it is undefined behavior whether or not a given build appears to work. If a legacy API takes char* but provably does not write, the honest repair is at the API's declaration, changing the parameter to const char*; the call site is not where that lie should be maintained.

Take the pointer at the point of use, and never store it. A c_str() or data() result is borrowed storage. Any non-const member call that can reallocate, and any hand-off of the string by non-const reference, can invalidate it. Code that needs the text later keeps the std::string, not the pointer.

Convert a view through a string when a terminator is required. A std::string_view's data() carries no null-termination guarantee. Build a std::string from the view and pass its c_str(); do not pass a substring view's pointer to a function that scans for a terminator.

Which fix for which error

  • cannot convert 'std::string' to 'const char*' at a call: the string itself was passed where a pointer belongs. Pass s.c_str() (or s.data()), at that call site.
  • invalid conversion from 'const char*' to 'char*' after adding c_str(): the API writes through its parameter. Pass s.data() on a non-const s, in C++17 or later, and confirm the API writes only inside the string's current length.
  • The same const error, but the string at hand is const: there is no pointer fix. Copy the string into a non-const local, or change the owning code so the string it hands out for writing is not const.
  • A crash or wrong text some time after a call that worked at first: a stored c_str() or data() pointer outlived a modification of its string. Keep the string, retake the pointer at each use.
  • A C function receiving more text than the program's variable holds, with a view involved: a substring view's data() was passed to a scanning function. Materialize a std::string from the view first.

Checklist

  • Name the receiving parameter's type from the note in the error, const char* or char*, before choosing the fix; the two errors look alike and take different functions.
  • Use c_str() for read-only parameters and data() on a non-const string for writable ones; never mix the writable route with a const string or a pre-C++17 standard setting.
  • Search the code for stored results of c_str() and data(): each stored pointer needs its string's lifetime and modification history named, or it is a dangling pointer waiting for a reallocation.
  • Check any char* API's contract for appending or writing past the current length; data() grants the existing characters, not spare capacity, and the terminating null is not writable storage.
  • Where a view meets a C API, check for a substring or a non-terminated source array before passing any data() pointer.
  • Treat [-fpermissive] in an error as a warning about the proposed workaround, not as the workaround.

Sources

  • cppreference, std::basic_string::c_str — for c_str() returning a pointer to a null-terminated character array with data equivalent to those stored in the string, for writing to the array accessed through c_str() being undefined behavior, and for the invalidation rule covering non-const member calls and passing a non-const reference to a standard library function.
  • cppreference, std::basic_string::data — for the const overload returning const CharT and the non-const overload returning CharT since C++17, for the array being null-terminated since C++11 with data() and c_str() performing the same function, for modifying the past-the-end null terminator to any value other than CharT() being undefined behavior, and for the same invalidation rule.
  • cppreference, std::basic_string::operator[] — for data() + i == std::addressof(operator[](i)) for every i in [0, size()], which is the identity behind both the historical &s[0] route and the guarantee that the pointer names the string's own characters in order.
  • cppreference, std::basic_string_view::data — for a view's data() returning a pointer to a buffer that is not necessarily null-terminated, for the substring view as the documented example, and for passing such a pointer to a routine expecting a null-terminated string being typically a mistake.

Keep Exploring