为什么以下C程序会出现总线错误?

我认为这是第一次失败的召唤。我写了C已经有一段时间了,我不知所措。非常感谢。
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
  char *str = "one|two|three";

  char *tok = strtok(str, "|");

  while (tok != NULL) {
    printf("%sn", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}
    
已邀请:
字符串文字应该分配给const char *,因为修改它们是未定义的行为。我很确定strtok修改了它的参数,这可以解释你看到的坏事。     
有两个问题: 制作
str
类型
char[]
。 GCC发出警告
foo.cpp:5: warning: deprecated conversion from string constant to ‘char*’
,表明这是一条有问题的线路。 你的第二个
strtok()
电话应该有
NULL
作为它的第一个参数。查看文档。 生成的工作代码是:
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
  char str[] = "one|two|three";

  char *tok = strtok(str, "|");

  while (tok != NULL) {
    printf("%sn", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}
哪个输出
one
two
three
    
我不确定是什么“总线”错误,但如果你想继续解析相同的字符串,循环中strtok()的第一个参数应为NULL。 否则,在第一次调用strtok()之后,顺便从第一个字符串的开头开始。     

要回复问题请先登录注册