c - 为什么下面的程序中要添加 '\0'?

标签 c string null-character

有人告诉我空字符或 ‍'\0' 的作用是识别字符串的结尾。

但是,我很困惑,因为到目前为止我遇到过两个程序,其中没有使用相同的(空字符)。

所有三个程序都处理 strlen(),我无法推断它在这个程序中的重要性和/或存在。

char st[20], rst [20]; // Edit: Added these string declarations!
int i, j;
printf("\n Enter the string : ");
scanf("%s",st);
i= 0;
j = strlen(st) - 1;
while (j >= 0)
{
    rst[i] = st[j];
    i++;
    j--;
}
rst[i] = '\0';
if(strcmp(st, rst) == 0)
    printf("\n %s is a palindrome string", st);
else
    printf("\n %s is not a palindrome string", st);

看起来包含或排除空字符不会影响结果。

但是,我很好奇为什么作者可能会发现有必要添加它。

最佳答案

包含空字符可保证第二个字符串以空字符结尾,因此结果是正确的。

尽管第二个字符串有可能首先以全零开头,但这意味着您不必分配空字符。但通常情况下,当你刚刚分配内存时,你无法预测 st 字符串的内容是什么。

关于c - 为什么下面的程序中要添加 '\0'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158963/

相关文章:

r - 使用字符串访问 data.table 列

php - 当字符串末尾时模式不匹配

c++ - 字符串中的重复字符

c++ - 什么是 union ?

c - 如何对64位寄存器的低32位进行BSWAP?

Java BufferedWriter 创建空字符

c# - 什么会导致 XML 文件被空字符填充?

C++ - 字符数组和空字符

c - 向 EMC Clariion 拍摄 SCSI Reservations & Release 的程序(在 Linux 上)

c++ - 用于 Objective C 的 IDE