std::basic_string<CharT,Traits,Allocator>::c_str
来自 cppreference.cn
< cpp | string | basic string
const CharT* c_str() const; |
(noexcept since C++11) (constexpr since C++20) |
|
返回指向空终止字符数组的指针,该数组的数据等效于存储在字符串中的数据。
该指针使得范围 [
c_str(),
c_str() + size()]
是有效的,并且其中的值对应于字符串中存储的值,并在最后一个位置之后附加一个空字符。
从 c_str()
获取的指针可能因以下情况而失效
- 将字符串的非常量引用传递给任何标准库函数,或者
- 在字符串上调用非常量成员函数,但排除 operator[], at(), front(), back(), begin(), rbegin(), end() 和 rend()(自 C++11 起)。
写入通过 c_str()
访问的字符数组是未定义行为。
|
(自 C++11 起) |
目录 |
[edit] 参数
(无)
[edit] 返回值
指向底层字符存储的指针。
c_str()[i] == operator[](i) 对于 |
(直到 C++11) |
c_str() + i == std::addressof(operator[](i)) 对于 |
(自 C++11 起) |
[edit] 复杂度
常数。
[edit] 注解
只有当字符串对象不包含其他空字符时,从 c_str()
获取的指针才能被视为指向空终止字符字符串的指针。
[edit] 示例
运行此代码
#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'
[edit] 参见
(DR*) |
访问首字符 (公共成员函数) |
(DR*) |
访问尾字符 (公共成员函数) |
返回指向字符串首字符的指针 (公共成员函数) |