我正在使用一个简单的程序,使用 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 ) {
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}
程序运行成功。但是,如果将 a 行更改为
char * str= "now # time for all # good men to # aid of their country"; //line a
strtok 函数提供核心转储。我想得到一个解释,以了解为什么会这样?因为从 strtok 的声明为 --char *strtok( char *str1, const char *str2 ); char *str 作为第一个参数应该有效
最佳答案
char *str = "foo"
给你一个指向字符串文字的指针(你真的应该做 const char *
,但是 C 允许非 const
出于向后兼容的原因)。
尝试修改字符串文字是未定义的行为。 strtok
修改其输入。
关于c - C中的strtok函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6265236/