std::basic_string<CharT,Traits,Allocator>::c_str
来自 cppreference.cn
< cpp | string | basic_string
const CharT* c_str() const; |
(C++11 起无异常抛出) (C++20 起为 constexpr) |
|
返回一个以空字符结尾的字符数组的指针,其数据等同于字符串中存储的数据。
该指针所指向的范围 [
c_str(),
c_str() + size()]
是有效的,其中的值与字符串中存储的值相对应,并在最后一个位置后附加了一个空字符。
通过 c_str()
获取的指针可能因以下情况失效:
- 将字符串的非 const 引用传递给任何标准库函数,或者
- 在字符串上调用非 const 成员函数,不包括 operator[]、at()、front()、back()、begin()、rbegin()、end() 和 rend()(C++11 起)。
通过 c_str()
访问的字符数组写入会导致未定义行为。
|
(C++11 起) |
目录 |
[编辑] 参数
(无)
[编辑] 返回值
指向底层字符存储的指针。
对于 |
(C++11 前) |
对于 |
(C++11 起) |
[编辑] 复杂度
常数时间。
[编辑] 注意
只有当字符串对象不包含其他空字符时,从 c_str()
获取的指针才能被视为指向以空字符结尾的字符串。
[编辑] 示例
运行此代码
#include <algorithm> #include <cassert> #include <cstring> #include <string> extern "C" void c_func(const char* c_str) { printf("c_func called with '%s'\n", c_str); } int main() { std::string const s("Emplary"); const char* p = s.c_str(); assert(s.size() == std::strlen(p)); assert(std::equal(s.begin(), s.end(), p)); assert(std::equal(p, p + s.size(), s.begin())); assert('\0' == *(p + s.size())); c_func(s.c_str()); }
输出
c_func called with 'Emplary'
[编辑] 参阅
(DR*) |
访问第一个字符 (public 成员函数) |
(DR*) |
访问最后一个字符 (public 成员函数) |
返回指向字符串第一个字符的指针 (public 成员函数) |