有人告诉我空字符或 '\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/