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

strstr() - C library function not finding string (needle) in string (haystack)

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

#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" 在后面的参数中以任何形式出现,它就会找到它。为什么会这样?

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

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

char needle[4] = "done";

strstr 期望 NUL 终止 char 数组。这里 strstr 不知道在哪里停止比较 - 你必须为 [=19=] 字符腾出空间。

char needle[5] = "done";

或者干脆

char needle[] = "done";

澄清:

知道没有错

char needle[4] = "done";

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

来自标准 §6.7.9

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