c++ - 与字符串文字不同,为什么具有单独字符的字符数组不以空终止符结尾?

标签 c++ arrays char sizeof null-terminated

我在 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/

相关文章:

c++ - Visual Studio 2019 C++多行注释

java - 如何在Java中创建通用数组?

java - 为什么当通过其他方法更改数组时,数组的打印结果会有所不同?

c - 在 C 中将 char 数组拆分为多个部分 : unexpected behaviour

C 编程 : EOF as a character

c++ - 在 C++0x 中未调用移动构造函数

c++ - 当我使用线程时,Breakpad 无法在目标上创建小型转储

c++ - () 和 = 在创建类实例时有什么区别?

java - 使用数组项设置按钮文本

c++ - 空格后的字符不会被打印出来