字元指標可以參考至一個字串常數,這使得字串的指定相當的方便,例如下面的程式片段宣告一個字串指標,並指向一個字串常數:
char *str = "hello";
使用字元指標的好處是,您可以直接使用指定運算子將一個字串常數指定給字元指標,例如:
str = "world";
下面這段程式是個簡單的示範:
#include <iostream>
using namespace std;
int main() {
char *str = "hello";
cout << str << endl;
str = "world";
cout << str << endl;
return 0;
}
執行結果:
在程式中使用一個字串常數時,該字串常數會佔有一個記憶體空間,例如"hello"與"world"都各佔有一塊記憶體空間,所以上面的程式str前後所指向的記憶體位址並不相同,下面這個程式可以印證:
#include <iostream>
using namespace std;
int main() {
char *str = "hello";
void *add = 0;
add = str;
cout << str << "\t"
<< add << endl;
str = "world";
add = str;
cout << str << "\t"
<< add << endl;
return 0;
}
執行結果:
hello 0x440000
world 0x440008 |
如上面的程式所示,"hello"字串常數的位址是在0x8048770,而"world"字串常數的位址是在0x804877a,兩個的位址並不相同。
要注意的是,如果使用陣列的方式宣告字串,則不可以直接使用=指定運算子另外指定字串,例如下面的程式是錯誤的示範:
char str[] = "hello";
str = "world"; // error, ISO C++ forbids assignment of arrays
在字元指標中使用指標陣列,可以更方便的處理字串陣列,例如:
#include <iostream>
using namespace std;
int main() {
char *str[] = {"professor", "teacher",
"student", "etc."};
for(int i = 0; i < 4; i++)
cout << str
<< endl;
return 0;
}
執行結果:
professor
teacher
student
etc. |
str中的每個元素都是字元指標,也各自指向一個字串常數,進一步擴充這個觀念,就可以使用二維以上的字串陣列,例如:
#include <iostream>
using namespace std;
int main() {
char *str[][2] = {"professor", "Justin",
"teacher", "Momor",
"student", "Caterpillar"};
for(int i = 0; i < 3; i++) {
cout << str[0] << ": "
<< str[1] << endl;
}
return 0;
}
執行結果:
professor: Justin
teacher: Momor
student: Caterpillar |
額外補充一點,下面兩個宣告的作用雖然類似,但其實意義不同:
char *str1[] = {"professor", "Justin", "etc."};
char str2[3][10] = {"professor", "Justin", "etc."};
第一個宣告是使用指標陣列,每一個指標元素指向一個字串常數,只要另外指定字串常數給某個指標,該指標指向的記憶體位址就不同了,而第二個宣告則是配置連續的3x10的字元陣列空間,字串是直接儲存在這個空間,每個字串的位址是固定的,而使用的空間也是固定的(也就是含空字元會是10個字元)。