【问题标题】:Bus Error:10 with strtok in C总线错误:10 与 C 中的 strtok
【发布时间】:2016-12-07 15:19:32
【问题描述】:

这是我的代码,当我运行代码时,总是总线错误 10:

void print_tokens(char *line)
{
    static char whitespace[] = " \t\f\r\v\n";
    char *token;

    for(token = strtok(line, whitespace);
       token != NULL;
       token = strtok(NULL, whitespace))
       printf("Next token is %s\n", token);
}

int main(void)
{
    char *line = "test test test";
    print_tokens(line);
    return 0;
}

请帮帮我!

【问题讨论】:

  • 另外,您上面的代码在for() 行的; 之前缺少)。 (很可能还有一些{}

标签: c


【解决方案1】:

您不能修改字符串常量。以这种方式定义line

char line[] = "test test test";

【讨论】:

    【解决方案2】:

    strtok 将修改它传递的缓冲区;这是contractual

    使用这些功能时要小心。如果您确实使用它们,请注意:

    * 这些函数修改了它们的第一个参数。

    * 这些函数不能用于常量字符串。

    当您在 C 中将字符串声明为 char *str = "blah blah"; 时,您将其声明为只读内存,因此当您将其传递给 strtok 时,结果未定义,因为 strtok 想要修改缓冲区但可以'不是因为它是只读的。

    要解决此问题,请将 str 声明为数组:char str[] = "blah blah";

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 2017-07-06
      • 2013-02-07
      相关资源
      最近更新 更多