目錄
1、char[]與char*
char s1[] = "hello";
讓我們解讀一下這種初始化方式和s1。
1、"hello"是一個字符串常量,保存在常量存儲區。因為賦值給了s1[],而s1[]是自動存儲類型的變量,所以拷貝了一份到棧中。
2、s1實際上是一個指針常量。其指向的地址不能變,但能通過s1改變其指向地址的值。
這時候可能有童鞋會問:既然s1是指針那為什么cout<<s1;可以輸出全部的字符呢,不是應該只輸出一個字符嗎???
這是因為cout內有很多<<的運算符重載,並會對一些類型進行了特別處理。比如char數組,當檢測其為這種類型時,會從指向的首位置開始連續輸出,直到遇見字符串終止符'\0'。
char* s2 = "hello";
1、"hello"是一個字符串常量,保存在常量存儲區。然后我們定義一個指針,直接指向"hello"所在常量區的地址的首地址。
2、s2實際上是一個常量指針。其指向的地址可以變,但不能通過s2改變其指向地址的值(因為s2指向的為常量區的地址,不能改變)。
2、題
char str1[] = "abc";
char str2[] = "abc";
const char str3[] = "abc";
const char str4[] = "abc";
const char *str5 = "abc";
const char *str6 = "abc";
char *str7 = "abc";
char *str8 = "abc";
cout << (str1 == str2) << endl;
cout << (str3 == str4) << endl;
cout << (str5 == str6) << endl;
cout << (str7 == str8) << endl;
char ch1 = 'a';
char ch2 = 'a';
const char ch3 = 'a';
const char ch4 = 'a';
cout << (ch1 == ch2) << endl;
cout << (ch3 == ch4) << endl;
3、答
輸出:
0
0
1
1
1
1
ch1 == ch2 比較的是值,並不是向上面那樣比較指針地址。ch1也不是指針。