gpt4 book ai didi

c - 为什么传入函数时字符串不会以空值终止?

转载 作者:行者123 更新时间:2023-11-30 19:56:53 25 4
gpt4 key购买 nike

这是我的电话:

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;
}
}

当我尝试使用 strchr() 迭代 str1 时,我的问题就开始了,它需要一个以 null 结尾的字符串。由于某种原因它一直循环。我不想使用 memchr()

为什么 str1str2 没有以 null 终止?我怎样才能终止它们?

最佳答案

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

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

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

来自 strchr 联机帮助页:

The terminating null character is considered to be part of the string; therefore if c is \0, the functions locate the terminating \0.

基本上,一旦到达 str2 中的空字符,就会匹配 str1 中的空字符。此后,您的循环将继续在 str1 之后的内存中查找出现在 str2 末尾之后的字符。困惑随之而来。

关于c - 为什么传入函数时字符串不会以空值终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13586751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com