5.2 字串
字串是字元的陣列
字串可以被視為一個字元型別的一維陣列,例如:"Hello world!"在記憶體中是這樣一個一個字元儲存的。
#include <iostream>
using namespace std;
int main()
{
char greeting[13] = "Hello world!";
cout << greeting;
return 0;
}

在上圖中最後一個字元 '\0'是什麼呢?這個是所謂的 null字元。因為每個字串的長度是不一定的,cout << greeting; 中,傳給 cout 的其實只是整個字串開頭在記憶體中的位址,cout 會逐個字元輸出,直到遇到 null 字元為止。所以雖然 "Hello world!" 只有 12 個字元長,但是我們準備了長度為 13 的 char 型別陣列來儲存它。
如果我們把程式改成這樣。
#include <iostream>
using namespace std;
int main()
{
char greeting[13] = "Hello world!";
cout << greeting; // 輸出: "Hello world!"
cin >> greeting; // 輸入: "Good"
cout << greeting; // 輸出: "Good"
return 0;
}
在第 11 行輸入 "Good" 之後,greeting 陣列的內容會變成這樣。
