C++ char[]和char*




参考博客

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也不是指针。

posted @ 2019-12-07 17:23  Fflyqaq  阅读(9169)  评论(0编辑  收藏  举报