##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::basic_string::c_str

From cppreference.com
< cpp‎ | string‎ | basic string

const CharT* c_str() const; |  |

Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.

The pointer is such that the range `[c_str(); c_str() + size()]` is valid and the values in it correspond to the values stored in the string with an additional null character after the last position.

The pointer obtained from `c_str()` may be invalidated by:

- Passing a non-const reference to the string to any standard library function, or
- Calling non-const member functions on the string, excluding operator[], at(), front(), back(), begin(), rbegin(), end() and rend().

Writing to the character array accessed through `c_str()` is undefined behavior.

`c_str()` and data() perform the same function. | (since C++11)

### [edit] Parameters

(none)

### [edit] Return value

Pointer to the underlying character storage.

data()[i] == operator[](i) for every `i` in `[0, size())`. | (until C++11)
data() + i == &operator[](i) for every `i` in `[0, size()]`. | (since C++11)

### [edit] Complexity

Constant.

### [edit] Exceptions

(none) | (until C++11)
`noexcept` specification: noexcept | (since C++11)

### [edit] Notes

The pointer obtained from `c_str()` may only be treated as a pointer to a null-terminated character string if the string object does not contain other null characters.

### [edit] Example

Run this code

    #include <algorithm>
    #include <cassert>
    #include <cstring>
    #include <string>

    int main()
    {
      std::string const s("Emplary");
      assert(s.size() == std::strlen(s.c_str()));
      assert(std::equal(s.begin(), s.end(), s.c_str()));
      assert(std::equal(s.c_str(), s.c_str() + s.size(), s.begin()));
      assert(0 == *(s.c_str() + s.size()));
    }

### [edit] See also

front (C++11) | accesses the first character (public member function) [edit]
back (C++11) | accesses the last character (public member function) [edit]
data | returns a pointer to the first character of a string (public member function) [edit]

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/string/basic_string/c_str&oldid=91560"
Category:

- unconditionally noexcept

Hidden categories:

- Pages with unreviewed unconditional noexcept template
- Pages with unreviewed noexcept template