gpt4 book ai didi

c - strstr() - C 库函数在字符串 (haystack) 中找不到字符串 (needle)

转载 作者:行者123 更新时间:2023-11-30 19:06:17 24 4
gpt4 key购买 nike

我有以下代码,它从命令行获取参数并大海捞针。

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

int main(int argc, char **argv)
{
int i, j, flag = 0;
for (i = 1; i < argc; i++)
{
char needle[4] = "done";
int length = strlen(argv[i]);

for (j = length - 1; j >= 0; j--)
{
// here is some simple code to print out the string
// in reverse order that I commented out.
argv[i][j] = tolower(argv[i][j]);
}

char *pch = strstr(argv[i], needle);
if (pch)
{
printf("DONE!");
}
//printf("%s", pch);
}

return 0;
}

现在,当我尝试输入以下参数时:

hi there done

我得到:

DONE!

但是如果我尝试这个:

done

我没有得到任何输出。

问题在于,如果有多个参数,它只会忽略第一个参数中出现的“done”,或者根本找不到它。另一方面,如果“done”在后面的参数中以任何形式出现,它就会找到它。为什么会发生这种情况?

最佳答案

这里有未定义的行为,因为使用非 nul 终止的字符数组调用 strstr

您已经像这样初始化了needle -

char needle[4] = "done";

strstr 需要 NUL 终止的 char 数组。这里 strstr 不会知道在哪里停止比较 - 你必须为 \0 字符腾出空间。

char needle[5] = "done";

或者简单地

char needle[] = "done";
<小时/>

澄清:

知道没有什么问题

char needle[4] = "done";

即使它没有存储\0,它也没有违反任何规则。该数组用done初始化。但是你将它传递给了一个具有不同期望的函数 - 这就是问题所在。标准库中处理字符串的大多数函数都需要 NUL 终止的 char 数组。

来自标准§6.7.9

An array of character type may be initialized by a character stringliteral or UTF−8 string literal, optionally enclosed in braces.Successive bytes of the string literal (including the terminating nullcharacter if there is room or if the array is of unknown size)initialize the elements of the array.

关于c - strstr() - C 库函数在字符串 (haystack) 中找不到字符串 (needle),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48357603/

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