std::basic_string<CharT,Traits,Allocator>::c_str
出自cppreference.com
< cpp | string | basic string
const CharT* c_str() const; |
(C++11 起為 noexcept) (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("以 '%s' 调用 c_func\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()); }
輸出:
以 'Emplary' 调用 c_func
[編輯] 參閱
(DR*) |
訪問首字符 (公開成員函數) |
(DR*) |
訪問最後的字符 (公開成員函數) |
返回指向字符串首字符的指針 (公開成員函數) |