[英]Null terminator at the end of char array in C++
为什么不必在以下代码中将名为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
区别在于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 );
要在第一个示例中的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我和j变量。 所以,你不再需要temp [j] ='\\ 0'了..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.