C 为什么传入函数时字符串不以null结尾?

C 为什么传入函数时字符串不以null结尾?,c,C,这是我的电话: testFunc(0,0,"+++++A+++b+c++++d+e++++f+g+++++h+i","Abcdefghi"); 该职能: 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, s

这是我的电话:

testFunc(0,0,"+++++A+++b+c++++d+e++++f+g+++++h+i","Abcdefghi");
该职能:

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));
}
这就要求:

    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;
    }
}
当我尝试使用
strhr()
遍历
str1
时,我的问题就开始了,它需要一个以null结尾的字符串。由于某种原因,它一直在循环。我不想使用
memchr()


为什么
str1
str2
没有被null终止?如何终止它们?

这两个字符串肯定以null结尾发生的情况是,您的代码经过空终止符进行迭代。

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

    int i = 1;
    while (pch != NULL && str2[i] != 0)
    {
        pch = strchr(pch + 1, str2[i++]);
    }
strchr
手册页:

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

基本上,一旦您到达
str2
中的空字符,就会匹配
str1
中的空字符。在此之后,循环继续查找
str1
后面的内存中出现在
str2
末尾之后的字符。混乱接踵而至。

使用

while (pch!=NULL && *(pch+1)!='\0' && str2[i]!='\0')
而不是

while (pch!=NULL)

正如其他人已经提到的,C样式字符串以“\0”结尾

你可能想看看。strstr查找s1中s2的位置。由于未使用参数
isRight
gap
,这将简化
extendedSubStr

int extendedSubStr(int isRight, int gap, const char* str1, const char* str2)
{
    char *r = strstr(str1, str2);
    return r != NULL ? r - str1 : -1;
}

您需要显示更多的代码。字符串将被终止,因此您的程序中肯定有其他错误。>为什么
str1
str2
不以null终止?我怎样才能终止他们?实际上,它们肯定是NUL终止的。您的问题可能存在于其他地方(可能在
extendedSubStr()
),但根据您提供的信息无法判断。我认为您需要仔细查看
extendedSubStr()
,并/或发布代码供我们查看。向我们展示完整的,使用重现问题所需的最少代码量的可编译示例。展示一个程序的片段会导致猜测,并使答案比需要的更难回答。我对此表示怀疑。我想看到的是一个单独的文件,从
#include
int main()
在一个代码块中,我可以使用
cat>test.c
和编译工具将其写入磁盘。20个人必须检查我们是否需要stdlib.h、string.h、stdio.h和其他一些文件,还要编写
main()
,这是一个巨大的浪费。如果您总是包含精确再现问题所需的最少代码量,您将得到更好的答案(以及我的自动向上投票)。