【发布时间】:2016-11-06 10:04:00
【问题描述】:
我正在尝试使用 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;
}
但是这个不行:
int main() {
char *str = "apple apple peach";
char *p;
p = strstr(str, "peach");
if (p!= NULL) {
strncpy(p, "apple", 5);
}
return 0;
}
这两个都不是:
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;
}
这两个都不是:
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;
}
这是一个已知的错误或功能吗?
【问题讨论】:
-
这不是
strstr的问题。您不能写入字符串常量。它被放入内存的只读部分。 -
致 OP:使用 -Wwrite-strings 编译以获取有关此问题的警告。
-
或使用 -Wall 和 -Wextra 更好,当您使用 gcc 或为您的编译器使用等效标志时。并检查每个警告。
-
@12431234123412341234123。请注意,-Wall -Wextranot 启用了 write-strings。以前是,但现在不是了。