C语言中模拟strcmp的输出错误

为什么运行的时候会出现100呢,
运行结果是
0
100
0
怎样才能分别输出
0
1
-1呢?是输入的str1,str2的字符不符合吗


#include 
int my_strcmp(const char* str1,const char* str2)
{
    // if the characters currently being compared are equal
    int ret;
    while (*str1 == *str2)
    {

        if (*str1 == '\0'&&*str2 == '\0')//When both str1 and str2 are 0
        {
            ret=0;
            break;
        }
        str1++;
        str2++;
    }
    if (*str1 > *str2)
    {
        ret=1;
    }
    else
    {
        ret=-1;
    }
}
int main()
{
    const char *str1="abcd";
    const char *str2="dcba";
    const char *str3="abc";
    int ret = my_strcmp(str1,str1);
    printf("%d\n",ret);
    ret = my_strcmp(str1,str2);
    printf("%d\n",ret);
    ret = my_strcmp(str1,str3);
    printf("%d\n",ret);
}

在你的代码中,my_strcmp函数没有返回值,所以 ret 的值是未定义的。因此,你在调用 my_strcmp 函数时可能会得到任意的结果。

为了使 my_strcmp 函数能够正常工作,你应该在函数的最后添加一个 return 语句来返回 ret 的值。例如:

int my_strcmp(const char* str1,const char* str2)
{
    // if the characters currently being compared are equal
    int ret;
    while (*str1 == *str2)
    {
 
        if (*str1 == '\0'&&*str2 == '\0')//When both str1 and str2 are 0
        {
            ret=0;
            break;
        }
        str1++;
        str2++;
    }
    if (*str1 > *str2)
    {
        ret=1;
    }
    else
    {
        ret=-1;
    }
    return ret; // Add a return statement here
}


修改后,你的代码应该能够正常工作,输出 0,1,-1。

希望这能帮到你!