char *s1 = "hello";
char s2[] = "hello";
【区别所在】
char *s1 的s1是指针变量,而指针是指向一块内存区域,它指向的内存区域的大小可以随时改变,但当指针指向常量字符串时,它的内容是不可以被修改的,否则在运行时会报错。
char s2[]的s2 是数组对应着一块内存区域,其地址和容量在生命期里不会改变,只有数组的内容可以改变
【内存模型】
+-----+ +---+---+---+---+---+---+
s1: | *======> | h | e | l | l | o |\0 |
+-----+ +---+---+---+---+---+---+
+---+---+---+---+---+---+
s2: | h | e | l | l | o |\0 |
+---+---+---+---+---+---+
示例代码:
#include <iostream>
int main()
{
char *s1 = "hello";
char s2[] = "hello";
char *s3 = s2; //★注意这句必须要★
char **s4 = &s3; //s2(char[])要用两步才能完成赋值
char **s5 = &s1; //s1(char*) 只需一步
char(*s6)[6] = &s2; //&s2等价于char(*)[6]:指向包含6个char型元素的一维数组的指针变量
printf("s1=[%s]\n", s1);
printf("s2=[%s]\n", s2);
printf("s3=[%s]\n", s3);
printf("s4=[%s]\n", *s4);
printf("s5=[%s]\n", *s5);
printf("s6=[%s]\n", s6);
printf("\n size of s1: %d \n", sizeof(s1));
printf("\n size of s2: %d \n", sizeof(s2));
system("pause");
return 0;
}
运行结果如下:
注:字符串比较不能使用等于号,只能使用strcmp函数;相同则返回0,反之返回非零值。
#include<iostream>
#include<string>
using namespace std;
char str[20] = { "hello hdu" };
char *pstr;
int main()
{
pstr = str;
cout << *str << endl; // h
cout << *pstr << endl; // h
*pstr++ = 'Y';
cout << *str << endl; // Y
cout << *pstr << endl; // e
cout << *(pstr-1) << endl; // Y
cout << *(pstr--) << endl; // e
system("pause");
return 0;
}