为什么strcmp失败了?

Ras*_*yak 1 c string codeblocks

我很遗憾在这个门户网站上提出这个问题.因为这可能是一个愚蠢的问题.但是,我正在努力找出为什么strcmp不起作用?我也写了我自己的strcmp,我发现s1并且rev不同于rev持有一些垃圾.请帮帮我哪里出错了?

void main()
{
int i,j;
 char rev[5];
 char s1[5]= "madam";
 for(i=strlen(s1)-1, j = 0; i>=0; j++, i--)
 {
  rev[j]=s1[i];
 }
 puts(rev);
 printf("\n");
 puts(s1);
if(strcmp(rev,s1) == 0)
{
printf("Palindrome!!! \n");

}
}
Run Code Online (Sandbox Code Playgroud)

而不是strcmp(rev, s1)我自己动手i_strcmp(rev, s1).

int i_strcmp(char *s1, char *s2)
{
    int i;
    for (i = 0; s1[i] && s2[i]; ++i)
    {
        /* If characters are same or inverting the 6th bit makes them same */
        if (s1[i] == s2[i] || (s1[i] ^ 32) == s2[i])
           continue;
        else
           break;
    }

    /* Compare the last (or first mismatching in case of not same) characters */
    if (s1[i] == s2[i])
        return 0;
    if ((s1[i]|32) < (s2[i]|32)) //Set the 6th bit in both, then compare
        return -1;
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

但它仍然没有工作,我试图调试它,并在转发中发现了一些垃圾值.但是当我将字符串打印到控制台时,它会向控制台提供正确的输出.

Jef*_*Son 7

所有函数都需要strlen,最后strcmp需要带有\ x00的字符串.您的阵列没有空间(5个字符).使用您自己的strcmp版本,您太依赖于最可能不存在的\ x00限制器.

你可以strncmp改用.或者有更大的阵列.