C++中char数组末尾的空终止符

Ahm*_*med 3 c++ arrays string initialization

为什么不必在以下代码中将名为temp的字符串末尾存储空字符

char source[50] = "hello world";
char temp[50] = "anything";
int i = 0;
int j = 0;

while (source[i] != '\0')
{
    temp[j] = source[i];
    i = i + 1;
    j = j + 1;
}
 cout << temp; // hello world
Run Code Online (Sandbox Code Playgroud)

而在下面的情况下,它是必要的

char source[50] = "hello world";
char temp[50];
int i = 0;
int j = 0;
while (source[i] != '\0')
{
    temp[j] = source[i];
    i = i + 1;
    j = j + 1;
}
cout << temp; // will give garbage after hello world
              // in order to correct this we need to put temp[j] = '\0' after the loop
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 9

区别在于temp的定义.

在第一种情况下

char temp[50] = "anything";
Run Code Online (Sandbox Code Playgroud)

temp已初始化.未从字符串文字中分配字符的所有元素均为零初始化.

在第二种情况下

char temp[50];
Run Code Online (Sandbox Code Playgroud)

temp未初始化,因此其元素包含任意值.

当temp具有静态存储持续时间时,存在第三种情况.在这种情况下,如果它被定义为

char temp[50];
Run Code Online (Sandbox Code Playgroud)

其所有元素都由零初始化.

例如

#include <iostream>

char temp[50];

int main()
{
    char source[50] = "hello world";
    int i = 0;
    int j = 0;
    while (source[i] != '\0')
    {
        temp[j] = source[i];
        i = i + 1;
        j = j + 1;
    }
    std::cout << temp;
} 
Run Code Online (Sandbox Code Playgroud)

还要考虑到使用标准C函数strcpy将源复制到temp 更安全有效.例如

#include <cstring>

//...

std::strcpy( temp, source );
Run Code Online (Sandbox Code Playgroud)