字符串的末尾會有會有\0用于標(biāo)志著字符串的結(jié)束,因此在字符數(shù)組的初始化和復(fù)制的時(shí)候需要防止字符串的越界。如"123456789"中有9個數(shù)字如果要存儲到字符數(shù)組中至少需要10個字節(jié)的空間。
代碼分析:
#include <iostream>
using namespace std;
int main(){
char str1[] = "hello alibaba";
char str2[] = "hello alibaba";
char* str3 = "hello alibaba";
char* str4 = "hello alibaba";
if(str1 == str2)
cout<< "str2 and str1 are in the same ";
else
cout<<"str1 and str2 are not in the same";
if(str3 == str4)
cout<< "str3 and str4 are in the same ";
else
cout<<"str3 and str4 are not in the same";
return 0;
}
對于字符串?dāng)?shù)組,c/c++會分配兩個長度為14字節(jié)的空間,并將hello alibaba分別拷貝進(jìn)去,兩個數(shù)組的初始地址不同,因此會得到不同的提示。

編譯器的警告
而str3和str4是兩個指針,系統(tǒng)不會為他們分配內(nèi)存,只需要讓他們指向
hello alibaba的內(nèi)存地址即可,常量字符串在內(nèi)存中只有一份拷貝,兩個指針指向的內(nèi)容是一致的。