ANSI C strstr() 不使用指针

Jan*_*ekx 0 c strstr strncpy string.h

我正在尝试使用 strstr() 在字符串中查找子字符串。仅使用 char[] 有效,char* 无效,导致分段错误。

所以这个正在工作:

int main() {
    char str[] = "apple apple peach";
    char *p;

    p = strstr(str, "peach");
    if (p!= NULL) {
        strncpy(p, "apple", 5);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但这一个不起作用:

int main() {
    char *str = "apple apple peach";
    char *p;

    p = strstr(str, "peach");
    if (p!= NULL) {
        strncpy(p, "apple", 5);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个既不是:

int main() {
    char *str = "apple apple peach";
    char *peach = "peach";
    char *p;

    p = strstr(str, peach);
    if (p!= NULL) {
        strncpy(p, "apple", 5);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

而这一个:

int main() {
    char *str = "apple apple peach";
    char peach[] = "peach";
    char *p;

    p = strstr(str, peach);
    if (p!= NULL) {
        strncpy(p, "apple", 5);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是一个已知的错误或功能吗?

jam*_*lin 5

你的问题是strstr,它与strncpy。在指针的情况下,您正在strncpy尝试写入常量字符串文字