传入函数时为什么字符串没有被终止?

Tom*_*Tom -2 c

这是我的电话:

testFunc(0,0,"+++++A+++b+c++++d+e++++f+g+++++h+i","Abcdefghi");
Run Code Online (Sandbox Code Playgroud)

功能:

void testFunc(int isRight, int step, const char* str1, const char* str2)
{
    static int testNum = 1;
    printf("test%d: %d\n", testNum++, extendedSubStr(isRight, step, str1, str2));
}
Run Code Online (Sandbox Code Playgroud)

那叫:

    int extendedSubStr(int isRight, int gap, const char* str1, const char* str2)
{
// find location of the first char
        char * pch;
        char * firstOcur;
        pch=strchr(str1,str2[0]);
        firstOcur = pch;
        int i=0;
        while (pch!=NULL)
        {
            i++;
            // find next char from the remaining string
            pch=strchr(pch+1,str2[i]);
        }

    if(i==strlen(str2))
    {
                    // return position of the first char
        return firstOcur-str1;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试迭代str1 使用strchr()期望空终止字符串时,我的问题开始了.它由于某种原因不断循环.我宁愿不使用memchr().

为什么str1str2没有被终止?我怎么能终止他们?

NPE*_*NPE 6

这两个字符串绝对是空终止的.会发生什么是您的代码迭代超过null终止符.

str2[i]到达时你需要停止迭代\0:

    int i = 1;
    while (pch != NULL && str2[i] != 0)
    {
        pch = strchr(pch + 1, str2[i++]);
    }
Run Code Online (Sandbox Code Playgroud)

strchr联机帮助页:

终止空字符被认为是字符串的一部分; 因此,如果c是\0,则函数定位终止\0.

基本上,会发生的是,一旦到达空字符str2,就匹配空字符str1.在此之后,循环继续查找出现str2在后续内存末尾的字符str1.随之而来的是混乱.