Giter Site home page Giter Site logo

Comments (3)

hurley25 avatar hurley25 commented on June 21, 2024

有没有测试的case呢?具体传入什么字符串会导致返回0呢?

from hurlex-doc.

UKeeySDis avatar UKeeySDis commented on June 21, 2024

如果两个字符串的长度和字符都相等才会返回0。比如字符串str1="test a"和字符串str2="test b",按照之前的源码当判断到两个字符串最后的字符ab时,由于不相等会出while循环,但是代码中进行了++操作,就直接到达两个字符串的结束符位置了,然后会进if(*str1 == '\0' && *str2 == '\0'这个条件,返回0,但是其实这两个字符串虽然长度相同但并不相等。
测试代码(调用了库中的strcmp做比较):

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

int my_strcmp(const char *str1, const char *str2)
{
    while (*str1 && *str2 && (*str1++ == *str2++))
	    ;
    if (*str1 == '\0' && *str2 == '\0') {
	    return 0;
    }

    if (*str1 == '\0') {
	    return -1;
    }
    return 1;
}

int main()
{
    char *str1 = "test a";
    char *str2 = "test b";

    printf("%d\n", my_strcmp(str1, str2));
    printf("%d\n", strcmp(str1, str2));

    return 0;

}

from hurlex-doc.

hurley25 avatar hurley25 commented on June 21, 2024

嗯, 是的,这个函数是有问题的。多谢指出问题,已经修复并提交。
同时字符串函数移动到头文件里了(inline函数放在.c里好奇怪,不知道当时从哪里来的代码)。

from hurlex-doc.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.