Chapter 3.2 字串 - TKU-ME-Lab/C-C-_tutorial GitHub Wiki
在C++中,將以字元陣列儲存字串 由於字串最後必須以"\0"做結尾,字元陣列的大小,應為儲存字串的字元數家1 以下語法將宣告字串變數:
char a[5] = "John";
char a[5] = {'J','o','h','n'};
下圖為字串的儲存與存取說明:
各別存取語法 a[0] a[1] a[2] a[3] a[4]
陣列元素 J o h n \0
EX:
char string[6] = {'A','B','C','D','E'};
或
char string1[5] = "ABCD";
EX:
char string2[2][6] = { {'A','B','C','D','E'},
{'F','G','H','I','J'} };
或
char string3[2][5] = {"ABCD","FGHI"};
EX:
char g[2][5] = {"ABC","FGHI"};
變數名稱 g[0][0] g[0][1] g[0][2] g[0][3] g[0][4]
資料 A B C \0 ???
變數名稱 g[1][0] g[1][1] g[1][2] g[1][3] g[1][4]
資料 F G H I \0
EX:
#include <iostream>
using namespace std;
int main()
{
char stars[6][80] = { "Robert Redford",
"Hopalong Cassidy",
"Lassie",
"Slim Pickens",
"Boris Karloff",
"Oliver Hardy"
};
int dice = 0;
cout << endl
<< " Pick a lucky star!"
<< " Enter a number between 1 and 6: ";
cin >> dice;
if (dice >= 1 && dice <= 6) // Check input validity
cout << endl // Output star name
<< "Your lucky star is " << stars[dice - 1];
else
cout << endl // Invalid input
<< "Sorry, you haven't got a lucky star.";
cout << endl;
system("pause");
return 0;
}
程式中宣告變數後,記憶體中會配置一塊區域,儲存該變數資料 每一塊記憶體區域都有各自的編號,稱之為位址 欲取得某變數記憶體空間的位址時,需使用取址運算子 "&", 語法如下:
&變數名稱