C++ char[]和char*



参考博客

1、char[]与char*

char s1[] = "hello";

让我们解读一下这种初始化方式和s1。

1、"hello"是一个字符串常量,保存在常量存储区。因为赋值给了s1[],而s1[]是自动存储类型的变量,所以拷贝了一份到栈中。

2、s1实际上是一个指针常量。其指向的地址不能变,但能通过s1改变其指向地址的值。

这时候可能有童鞋会问:既然s1是指针那为什么cout<<s1;可以输出全部的字符呢,不是应该只输出一个字符吗???
这是因为cout内<<重载对其进行了特别处理,当检测其为这种类型时,会让其输出全部的字符。

char* s2 = "hello";

1、"hello"是一个字符串常量,保存在常量存储区。因为指针存储的是地址,所以s2直接指向"hello"在常量区的地址。

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

猜你喜欢

转载自www.cnblogs.com/Fflyqaq/p/12002635.html