gpt4 book ai didi

C: 当 Haystack 中找不到 Needle 时,my_strstr 返回 Needle

转载 作者:行者123 更新时间:2023-11-30 17:10:33 25 4
gpt4 key购买 nike

我的第一个堆栈溢出问题,所以我希望它格式正确。

我制作了一个模拟 strstr 的简单函数:

char *my_strstr(char *haystack, char *needle)
{
int i;

if (!needle || !*needle)
return (haystack); // if s2 is empty
while (*haystack != '\0')
{
i = 0;
while (*haystack != *needle && *haystack != '\0')
haystack++;
while (haystack[i] == needle[i] && haystack[i] != '\0')
i++;
if (needle[i] == '\0')
return (haystack);
haystack++;
}
return (0);
}

为了测试它,我有以下主要内容:

int     main(void)
{
char *haystack = "Stacy Lives Next Door Fool";
char *needle = "Stb";
char *ptr;

ptr = my_strstr(haystack, needle);
printf("%s\n", ptr);
return (0);
}

当我编译它时,它适用于所有场景,除了在干草堆中根本找不到针的情况。事实上,在这种情况下,“Stb”(针的值)会显示在屏幕上。有人可以向我解释为什么会这样吗?预先感谢您!

最佳答案

我刚刚写了同样的代码here 。对于 my_strstr 中的 char *,请勿 return (0),它会按示例的预期工作

关于C: 当 Haystack 中找不到 Needle 时,my_strstr 返回 Needle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32813872/

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