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

时间:2014-02-15 13:56:21

标签: 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

虽然在下面的情况下有必要

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

2 个答案:

答案 0 :(得分:9)

区别在于temp的定义。

在第一种情况下

char temp[50] = "anything";

temp已初始化。所有未从字符串文字中分配字符的元素都是零初始化。

在第二种情况下

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] != '\0')
    {
        temp[j] = source[i];
        i = i + 1;
        j = j + 1;
    }
    std::cout << temp;
} 

另外考虑到使用标准C函数strcpy将源复制到temp会更安全有效。例如

#include <cstring>

//...

std::strcpy( temp, source );

答案 1 :(得分:0)

要在第一个示例中的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(在源数组的长度),此位置已经通过定义初始化为0和i和j变量的声明。 所以,你不再需要temp [j] ='\ 0'..