我在 C++ 中使用 char 数组并编写了这个程序:
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 初始化 char 数组末尾没有空终止符 (0) 是否有特殊原因?
最佳答案
花括号初始化器只是为一个数组提供指定的值(或者如果数组更大,其余的项目是默认的)。即使项目是 char
值,它也不是字符串。 char
只是最小的整数类型。
字符串文字表示以零结尾的值序列。
就这些。
关于c++ - 与字符串文字不同,为什么具有单独字符的字符数组不以空终止符结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49695874/