关于函数:为什么strcmp在c中不起作用?

why is strcmp not working in c?

本问题已经有最佳答案,请猛点这里访问。

我刚刚开始学习c,并且想尝试strcmp函数,但是如果我运行它,总会以某种方式为我提供结果" 1"。 键入什么字符串都没有关系。由于第一个字符串短于第二个字符串,因此我期望结果为" -1"。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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,但也没有用。 网络并尝试自己解决它,可能只是一个简单的错误,如果有人可以帮助,我们将非常高兴。


libc中的strcmp几乎总是用以下代码等效:

1
2
3
4
5
6
7
8
9
10
int strcmp(char *s1, char *s2)
{
    for(; *s1 && *s2; s1++, s2++)
    {
        int res = *s1-*s2;
        if (res)
            return res;
    }
    return *s1-*s2;
}

它返回比较的第一个不同字符之间的差,以确保结果符合两个字符串关系== < >

当字符串长度不同时,返回值是较短的\0字符串结尾与另一个字符串的位置对应字符之间的差。 因此,结果还应反映出长度差。

根本不要期望0、1和-1。


看一下这个小程序,它的结构类似于您自己的程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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
"
, i);

  return 0;
}

编译并运行它,它返回一个负整数。 (它在我的gcc框上返回-1。)

这是因为" strcmp函数根据s1所指向的对象是小于,等于还是大于s2所指向的对象而返回负,零或正整数"。