簡體   English   中英

string.h的strcmp和我自己的strcmp實現之間的區別

[英]Difference between strcmp of string.h and my own implementation of strcmp

第一個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;
}

我理解,在我的實現中,代碼計算0(Null的ASCII) - 's'(ASCII值115)。 任何人都可以幫助我如何完全復制string.h中的strcmp函數的工作

在不相等的情況下從strcmp返回的確切值未明確定義。 在您的特定情況下,任何負值都被視為有效。 手冊頁

如果找到s1(或其前n個字節),則strcmp()和strncmp()函數返回小於,等於或大於零的整數,小於,匹配或大於s2 。

所以唯一的保證是,如果第一個參數是“小於”第二個,那么結果是負數,如果第一個參數是“大於”第二個,那么結果是正數。 不同的實現可以為相同的字符串返回不同的值。

例如,如果我在我的機器上編譯並運行您的代碼並將優化設置為-O0 ,那么我將從strcmp返回-115。 如果我將優化更改為-O1 ,則返回-1。 因此,結果不僅可以從一台機器更改為下一台機器,而且甚至可以在具有不同編譯器設置的同一台機器上發生變化。

在您的平台上實現“真正的” 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
}

BTW:它應該是int strcmp(const char *s, const char *t)而不是int strcmp(char *s, char *t)

manuel頁面說strcmp()函數比較兩個字符串s1和s2。 如果找到s1,則它返回小於,等於或大於零的整數,小於,匹配或大於s2。 你可以試試這段代碼:

    int ft_strcmp(const char *s1, const char *s2)
{
    while ((unsigned char)*s1 || (unsigned char)*s2)
    {
        if ((unsigned char)*s1 != (unsigned char)*s2)
            return ((unsigned char)*s1 - (unsigned char)*s2);
        s1++;
        s2++;
    }
    return (0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM