C中strtok函数出错
我正在使用一个简单的程序使用strtok函数标记字符串。这是密码-C中strtok函数出错,c,strtok,string,C,Strtok,String,我正在使用一个简单的程序使用strtok函数标记字符串。这是密码- # include <stdio.h> char str[] = "now # time for all # good men to # aid of their country"; //line a char delims[] = "#"; char *result = NULL; result = strtok( str, delims ); while( result != NULL ) { pri
# include <stdio.h>
char str[] = "now # time for all # good men to # aid of their country"; //line a
char delims[] = "#";
char *result = NULL;
result = strtok( str, delims );
while( result != NULL ) {
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}
strtok函数提供内核转储。我想为我的理解得到一个解释,为什么会这样?因为strtok声明为--char*strtok(char*str1,const char*str2);char*str作为第一个参数应该有效您不能修改字符串文字。这是最好的解释。简而言之,如果你声明
char *stuff = "Read-only stuff";
你不能修改它
strtok接受一个char*
的事实与不能将数组传递给函数有关,只能传递地址。这里可能会有所帮助。char*str=“foo”
为您提供一个指向字符串文字的指针(您确实应该执行const char*
,但出于向后兼容的原因,C允许使用非const
)
试图修改字符串文字是未定义的行为<代码> Strtok 修改其输入。
前面的答案给出了所需的答案,但是附加的信息:您可能想考虑使用StruUp()来创建字符串的副本,然后您可以在Strtok()中使用它。只需保留一个指向原始返回缓冲区的指针,因为完成时需要释放()它,因为它是malloced。
数组不是指针,指针也不是数组。你可能会喜欢,尤其是第6节。char *stuff = "Read-only stuff";