2010-08-11 151 views
10

C字符串和C++字符串有什麼區別?特別而做動態內存分配C字符串和C++字符串有什麼區別?

+0

你是指在兩種語言中使用'char *'和'char []'字符串或基於'char'的字符串和'std :: string'之間的區別? – dmckee 2010-08-11 02:43:19

+1

請定義「C string」和「C++ string」的含義。兩者(特別是後者)都不明確。 – strager 2010-08-11 02:43:36

+0

閱讀http://www.cplusplus.com/reference/string/string/和http://www.macdonald.egate.net/CompSci/hstrings.html – 2010-08-11 02:44:36

回答

22

我幾乎不知道從哪裏開始:-)

在C中,字符串只是char陣列其中,按照慣例,年底用NULL字節。在動態內存管理方面,你可以簡單地爲它們提供空間(包括額外的字節)。修改字符串時內存管理是責任:

char *s = strdup ("Hello"); 
char *s2 = malloc (strlen (s) + 6); 
strcpy (s2, s); 
strcat (s2, ", Pax"); 
free (s); 
s = s2; 

在C++中,字符串(std::string)與所有相關的自動化存儲管理和控制,這使得他們很多更安全和更容易使用的對象,尤其是對新手。對於動態分配,使用類似:

std::string s = "Hello"; 
s += ", Pax"; 

我知道我倒是喜歡使用,後者。您可以(如果您需要)始終使用c_str()方法從std::string中構建一個C字符串。

+2

'std :: string'是對象... – dmckee 2010-08-11 02:56:51

+0

該死的你c_str()! – 2010-08-11 06:11:06

6

C++字符串是更安全,更方便,並且支持不同的字符串操作的功能,如追加,發現,複製,級聯等

C字符串和c串之間++一個有趣的差異是通過下面的示例

所示
#include <iostream>        
using namespace std; 

int main() { 
    char a[6]; //c string 
    a[5]='y'; 
    a[3]='o'; 
    a[2]='b'; 
    cout<<a; 
    return 0; 
} 

輸出»¿boRy¤£·F·裨»¿

#include <iostream> 
using namespace std; 
int main() 
{ 
    string a; //c++ string 
    a.resize(6); 
    a[5]='y'; 
    a[3]='o'; 
    a[2]='b'; 
    cout<<a; 
    return 0; 
} 

輸出男孩

我希望你明白了!

+0

這種來自C的行爲是造成Heartbleed等錯誤的原因。 – saolof 2017-02-12 09:57:40

相關問題