#include<iostream>
using namespace std;
int main()
{
char s[] = { 'a','b','c','d','e' };
char* s1 = "a";
char* s2 = "ab";
char* s3 = "abc";
char* s4 = "abcd";
char* s5 = "abcde";
cout << "sizeof(s1) = " << sizeof(s1) << endl;
cout << "sizeof(s2) = " << sizeof(s1) << endl;
cout << "sizeof(s3) = " << sizeof(s1) << endl;
cout << "sizeof(s4) = " << sizeof(s1) << endl;
cout << "sizeof(s5) = " << sizeof(s1) << endl;
char s6[] = "a";
char s7[] = "ab";
char s8[] = "abc";
char s9[] = "abcd";
char s10[] = "abcde";
cout << endl <<"****************************" << endl;
cout << "sizeof(s6) = " << sizeof(s6) << endl;
cout << "sizeof(s7) = " << sizeof(s7) << endl;
cout << "sizeof(s8) = " << sizeof(s8) << endl;
cout << "sizeof(s9) = " << sizeof(s9) << endl;
cout << "sizeof(s10) = " << sizeof(s10) << endl;
cout << endl;
return 0;
}
其中sizeof()计算的是字符数组的真实大小,包括结尾的'\0' , 但是对于char* 类型来说,值是由电脑系统决定的,或者4或者8,与char* 所指向的字符串的长度一点关系都没有。
① char s[] = { 'a','b','c','d','e' };
②char* s5 = "abcde";
③char s10[] = "abcde";
这种初始化方式中,由上图可见,后两种系统会自动的赋予'\0' , 但是第一种不会有'\0' 因此无法用一切和'\0'有关的函数与遍历方法,即使手动赋值也不可以,因为没有给定数组长度,现在s数组是固定的长度,无法改变。
除非初始化的时候指明长度 char s[6] = { 'a','b','c','d','e' }; 像这样 s[5]也会被自动的赋予'\0';
可以用sizeof(s)/sizeof(char) 来 确定第一种数组中 元素的个数.