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

Null terminator at the end of char array in C++

本文关键字:终止 char 数组 C++      更新时间:2023-10-16

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

char source[50] = "hello world";
char temp[50] = "anything";
int i = 0;
int j = 0;
while (source[i] != '')
{
    temp[j] = source[i];
    i = i + 1;
    j = j + 1;
}
 cout << temp; // hello world

而在下面的情况下,它变得必要

char source[50] = "hello world";
char temp[50];
int i = 0;
int j = 0;
while (source[i] != '')
{
    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] = '' after the loop

区别在于温度的定义。

在第一种情况下

char temp[50] = "anything";

临时初始化。未从字符串文本中分配字符的所有元素都初始化为零。

在第二种情况下

char temp[50];

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

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

char temp[50];

它的所有元素都由零初始化。

例如

#include <iostream>
char temp[50];
int main()
{
    char source[50] = "hello world";
    int i = 0;
    int j = 0;
    while (source[i] != '')
    {
        temp[j] = source[i];
        i = i + 1;
        j = j + 1;
    }
    std::cout << temp;
} 

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

#include <cstring>
//...
std::strcpy( temp, source );

要在第一个示例中的 temp[] 定义中添加一些内容,请使用以下代码:

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

你看,源(strlen)的长度是12,temp的长度是9.你还初始化了变量i和j为零。

内存中 i 和 j 变量的位置实际上就在 temp 数组之后。因此,对于临时数组,在位置 12(在源数组的长度处),该位置已经通过 i 和 j 变量的定义和声明初始化为 0。所以,你不再需要 temp[j] = '\0' 了。