【发布时间】:2014-04-04 23:46:13
【问题描述】:
我有一个无法解决的问题。我将一个字符串拆分为子字符串并将这些子字符串放入一个数组中。一切都很好,直到搜索功能结束。 strtok 函数生成完美的子字符串,然后将所有内容都很好地放入数组中,但是当函数结束时,数组会丢失所有内容。我尝试了很多不同的东西,但似乎没有任何效果。我希望 words 数组在搜索功能结束并返回 main 时保留他的内容。
int main(void)
{
char** words=NULL;
char argument[26] = "just+an+example";
search(argument, words);
}
search(char* argument, char** words)
{
char* p = strtok (argument, "+");
int n_spaces = 0;
while (p)
{
words = realloc(words, sizeof(char*)* ++n_spaces);
if (words == NULL)
exit(-1); // memory allocation failed
words[n_spaces-1] = p;
p = strtok(NULL, "+");
}
// realloc one extra element for the last NULL
words = realloc(words, sizeof(char*)* (n_spaces+1));
words[n_spaces] = 0;
}
【问题讨论】:
-
请用适当的缩进格式化您的代码。
-
您不会为单独的单词复制数据,而只是将指针保存到现有数据拆分的地方。这意味着当您的源字符串超出范围时,这些指针将停止有效,此时数据可能会被覆盖等。这可能是您的代码中发生的事情吗?
-
@Rup 所以你说而不是 words[n_spaces-1] = p 我必须为每个 words[n_spaces-1] 进行 malloc,然后 strcpy p 到 words[n_space-1]?
-
如果这实际上是您的问题,是的,尽管使用
strdup(argument)和strtok复制会更简单。 (之后free也更简单。) -
C++ realloc 使用 NULL 指针; C stdlib 可能不会。尝试将单词初始化为 malloc(1) 而不是 NULL