命名空间
变体
操作

std::basic_string<CharT,Traits,Allocator>::c_str

来自 cppreference.cn
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
const CharT* c_str() const;
(C++11 起无异常抛出)
(C++20 起为 constexpr)

返回一个以空字符结尾的字符数组的指针,其数据等同于字符串中存储的数据。

该指针所指向的范围 [c_str()c_str() + size()] 是有效的,其中的值与字符串中存储的值相对应,并在最后一个位置后附加了一个空字符。

通过 c_str() 获取的指针可能因以下情况失效:

通过 c_str() 访问的字符数组写入会导致未定义行为。

c_str()data() 执行相同的功能。

(C++11 起)

目录

[编辑] 参数

(无)

[编辑] 返回值

指向底层字符存储的指针。

对于 [0size()) 中的每个 ic_str()[i] == operator[](i)

(C++11 前)

对于 [0size()] 中的每个 ic_str() + i == std::addressof(operator[](i))

(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 成员函数) [编辑]