char s[] = "wangshihui";
char *s = "wangshihui";
皆宣告了s字符串,在C-style string的函数皆可使用,但两者背后意义却不相同。
char s[] = "wangshihui"; s指向栈内存
的s是个char array,含11个byte(包含结尾\0),"wangshihui"对s来说是initializer,将字符一个一个地copy进s阵列。
char *s = "wangshihui"; s指向文字常量区,指向的内容为const 相当于const char *s="wangshihui"
的s是一个pointer指向char,由于"wangshihui"本身就是一个string literal,所以s指向"wangshihui"这个string literal的起始存储器位置。
char s1[] = "wangshihui";
char *s2 = "wangshihui";
cout << "size of s1: " << sizeof(s1) << endl;
cout << "size of s2: " << sizeof(s2) << endl;
s1是字符串数组,所以占了11byte(包含字符串结束标志);
而s2只是pointer,所以占了4 byte
实际使用有什么不同吗?两种写法皆可使用substring和pointer写法,但只有char *s可以直接使用*s++写法。
char s[]为阵列,虽然s == &s[0],但s是『常数』,恒等于&s[0]无法改变,但char *s为pointer,指向s[0],但却是变量,可以任意改变,故可用*s++任意更改pointer值。
Conclusion
一般人很少分辨char s[]和char *s的差异,大部分状况下用法相同,但char *s速度略快,因为不需copy的动作,且*s++为C语言常用的写法。
#include <iostream>
#include <cstring>
using namespace std; int main()
{
char s1[] = "wangshihui";
char *s2 = "wangshihui";
cout << "size of s1: " << sizeof(s1) << endl;
cout << "size of s2: " << sizeof(s2) << endl;
cout<<"\n----------\n";
for(int i = 0; i != sizeof(s1)-1; ++i)
{
cout << s1[i];
}
cout<<"\n----------\n";
for(int i = 0; i != strlen(s2); ++i)
{
cout << *(s2 + i);
}
cout<<"\n----------\n";
while(*s2)
cout << *s2++;
cout<<"\n----------\n";
/************
while(*s1)//编译不通过:lvalue required as increment operand|
cout << *s1++;
*************/
}
/************************
size of s1: 11
size of s2: 4 ----------
wangshihui
----------
wangshihui
----------
wangshihui
---------- **************************/