string.h的strcmp与我自己的strcmp实现之间的区别

suk*_*996 5 c string pointers

第一个printf输出为-1,而第二个printf输出为-115。

#include<stdio.h>
#include<string.h>
int mystrcmp(char*s, char*t){
    for(;*s==*t;s++,t++){
        if(*s=='\0'){
            return 0;
        }
    }
    return (*s-*t);
}
int main()
{
    char *y,*x="this";
    y="thiss";
    printf("%d\n\n",strcmp(x,y));
    printf("%d",mystrcmp(x,y));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我了解,在我的实现中,代码正在计算0(ASCII为Null)-'s'(ASCII值115)。任何人都可以帮助我如何精确复制string.h中的strcmp函数的工作吗

dbu*_*ush 10

strcmp在不相等的情况下返回的确切值没有明确定义。在您的特定情况下,任何负值均视为有效。从手册页

如果发现s1(或其前n个字节)分别小于,匹配或大于s2,则strcmp()和strncmp()函数将返回小于,等于或大于零的整数。 。

因此,唯一的保证是,如果第一个参数“小于”第二个参数,则结果为负;如果第一个参数“大于”第二个参数,则结果为正。不同的实现可能为相同的字符串返回不同的值。

举例来说,如果我在优化设置为的机器上编译并运行您的代码-O0,则我从-115返回strcmp。如果将优化更改为-O1,则返回-1。因此,结果不仅可以从一台计算机更改为另一台计算机,而且在具有不同编译器设置的同一台计算机上甚至可以有所不同。


Jab*_*cky 2

您的平台上“真实”的实现strcmp很可能接近此代码:

int strcmp(const char *s, const char *t) {
    for(; *s == *t; s++, t++) {
        if (*s == '\0') {           // are we at the end ?
            return 0;               // yes
        }
    }
    return (*s-*t) > 0 ? 1 : -1;   // return either +1 or -1
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句:它应该int strcmp(const char *s, const char *t)代替int strcmp(char *s, char *t)