std::basic_string<CharT,Traits,Allocator>::c_str
來自 cppreference.com
< 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 成員函式) |