为什么 strcmp 在 c 中不起作用?

why is strcmp not working in c?

我刚开始学习 c,我想试试 strcmp 函数,但如果我 运行 它总是给我结果“1”。不管我输入什么字符串。由于第一个字符串比第二个字符串短,我希望结果为“-1”。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



int main()
{
char array1[]="na";
char array2[]="kskkjnkjnknjd";
int i;

i= strcmp(array1,array2);

printf(" %d", i);

    return 0;
}

我也已经尝试摆脱 i 变量并只写 "printf(" %d", strcmp(array1, array2)); 并用 %u 替换 %d,但也没有用.我已经在网上搜索并尝试自己弄清楚了,可能只是一个简单的错误,如果有人能提供帮助,我会很高兴。:)

看看这个小程序,它的结构有点像您自己的程序。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
  char array1[]="a";
  char array2[]="b";
  int i;

  i = strcmp(array1,array2);

  printf(" %d\n", i);

  return 0;
}

编译并运行那个,它returns一个负整数。 (它 returns -1 在我的 gcc 盒子上。)

那是因为"the strcmp function returns a negative, zero, or positive integer depending on whether the object pointed to by s1 is less than, equal to, or greater than the object pointed to by s2."

strcmp 在 libc 中几乎总是用以下等价物编码:

int strcmp(char *s1, char *s2)
{
    for(; *s1 && *s2; s1++, s2++)
    {
        int res = *s1-*s2;
        if (res)
            return res;
    }
    return *s1-*s2;
}

它return是第一个不同比较字符之间的区别,这确保结果符合两个字符串关系== < >.

当字符串长度不同时,return 是较短字符串的 [=15=] 字符串结尾与另一个字符串的对应字符位置之间的差异。所以结果也应该反映长度差异。

不要期待 0、1 和 -1。