我有以下代码来按标记分割字符串:
char **strToWordArray(char *str, const char *delimiter)
{
char **words;
int nwords = 1;
words = malloc(sizeof(*words) * (nwords + 1));
int w = 0;
int len = strlen(delimiter);
words[w++] = str;
while (*str)
{
if (strncmp(str, delimiter, len) == 0)
{
for (int i = 0; i < len; i++)
{
*(str++) = 0;
}
if (*str != 0) {
nwords++;
char **tmp = realloc(words, sizeof(*words) * (nwords + 1));
words = tmp;
words[w++] = str;
} else {
str--;
}
}
str++;
}
words[w] = NULL;
return words;
}
如果我这样做:
char str[] = "abc/def/foo/bar";
char **words=strToWordArray(str,"/");
那么程序就可以正常工作,但如果我这样做:
char *str = "abc/def/foo/bar";
char **words=strToWordArray(str,"/");
然后我遇到了段错误。
这是为什么呢?该程序预计 char*
作为一个论点,为什么 char*
参数使程序崩溃?
最佳答案
因为该函数包含:
*(str++) = 0;
它修改传递给它的字符串。当你这样做时:
char *str = "abc/def/foo/bar";
str
指向只读字符串文字。请参阅此问题中标题为尝试修改字符串文字的部分:
关于c - 传递 char* 作为参数会破坏程序,而 char[] 不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45852135/