【发布时间】:2016-01-19 00:45:31
【问题描述】:
所以这是一个从 2 个不同文件中读取 3 个字符串 (orig // test1 // orig_copy) 的代码 (firstline // secondline)** 并调用 divide_string 以使用 strtok 和获取令牌并将它们存储在 **(token_orig // token_test // token_orig_copy) 中, -->这就是问题所在: - 当我将三行放在 main 中时,它会编译并从所有 3 个字符串和“完成”中获取令牌。到底。 - 但是当我尝试接下来的三行时(注意我如何将“HAHAHAH”更改为“HAHAHAHA”,这个小小的改变会改变一切并使程序停止在 printf("对于第二个字符串 :"); 。 我希望我解决了这个问题 PS:你可以过去复制程序,这样你就可以轻松编译自己了
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char s[4] = " ,.";
int divide_string(char* thestring,char** destination)
{
int i=0;
char* token=strtok(thestring,s);
destination[i]=malloc(sizeof(token)+1);
strcpy(destination[i],token);
i++;
printf("the word %d is 'tokened' \n",i);
while(token!=NULL)
{
token =strtok(NULL,s);
if (token != NULL)
{
destination[i]=malloc(sizeof(token)+1);
strcpy(destination[i],token);
printf("the word %d is 'tokened' \n",i);
++i;
}
}
return i;
}
void main ()
{ //TRY THESE THREE LINES THAT WORKS<-----------------------------
char orig[]= "does work HAHAHAH";
char orig_copy[] = "does work HAHAHAH";
char test1[]="does work HAHAHAH";
// char orig[]= "doesnt work HAHAHAHA";
// char orig_copy[] = "doesnt work HAHAHAHA";
// char test1[]="doesnt work HAHAHAHA";
char *token_orig[81];
char *token_test[81];
char *token_orig_copy[81];
strcpy(orig_copy,orig);
printf("for string number one : \n");
int max_orig = divide_string(orig,token_orig);
printf("for string number two : \n");
int a = divide_string(orig_copy,token_orig_copy);
printf("for string number three : \n");
int max_test = divide_string(test1,token_test);
printf("%s-",token_orig[0]);
printf("%s-",token_orig[1]);
printf("%s-\n",token_orig[2]);
printf("%s-",token_orig_copy[0]);
printf("%s-",token_orig_copy[1]);
printf("%s-\n",token_orig_copy[2]);
printf("%s-",token_test[0]);
printf("%s-",token_test[1]);
printf("%s-\n",token_test[2]);
printf("done .");
return 0;
}
【问题讨论】:
-
请编辑您的问题并定义“...不起作用...”在这种情况下的含义。看起来您正在使用名为
s的东西来定义分隔符,但在任何地方都没有定义s。如果您发布可以编译的内容,这将有所帮助。谢谢。 -
“不起作用”是什么意思?
-
malloc(sizeof(token)+1);bad bad bad, -->malloc(strlen(token)+1);即使那样,你也必须检查token != NULL -
还有各种各样的错误。你不检查
fopen或fgets的结果,你复制一个字符串然后从both 中删除newline, -
请创建并发布MCVE,而不是仅从您的代码中摘录。