我在 C++ 中玩弄字符数组并编写了这个程序:
int main()
{
char text[] = { 'h', 'e', 'l', 'l', 'o' }; //arrays initialised like this
//will have a size of the number
//of elements that you see
char text2[] = "hello"; //arrays initialised like this will have a size of
//the number of elements that you see + 1 (0 on the
//end to show where the end is
cout << endl;
cout << "The size of the first array is: " << sizeof(text) << endl;
cout << endl;
for (int i = 0; i < sizeof(text); i++)
{
cout << i << ":" << text[i] << endl;
}
cout << endl;
cout << "The size of the first array is: " << sizeof(text2) << endl;
cout << endl;
for (int i = 0; i < sizeof(text2); i++)
{
cout << i << ":" << text2[i] << endl;
}
cout << endl;
cin.get();
return 0;
}
这个程序给了我输出:
The size of the first array is: 5
0:h
1:e
2:l
3:l
4:o
The size of the first array is: 6
0:h
1:e
2:l
3:l
4:o
5:
我的问题是:与使用字符串文字初始化 char 数组不同,使用单独的字符初始化 char 数组是否有特殊原因在末尾没有空终止符 (0)?
花括号初始值设定项只是为数组提供指定的值(或者如果数组更大,则其余项是默认值)。即使项目是char
值,它也不是字符串。char
只是最小的整数类型。
字符串文字表示以零结尾的值序列。
就这样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句