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

发布于 2024-10-07 23:29:50 字数 322 浏览 0 评论 0原文

我认为这是第一个失败的 strtok 调用。好久没写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("%s\n", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}

I think it's the very first strtok call that's failing. It's been a while since I've written C and I'm at a loss. Thanks very much.

#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("%s\n", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紙鸢 2024-10-14 23:29:50

字符串文字应分配给 const char*,因为修改它们是未定义的行为。我很确定 strtok 修改了它的参数,这可以解释你看到的不好的事情。

String literals should be assigned to a const char*, as modifying them is undefined behaviour. I'm pretty sure that strtok modifies it's argument, which would explain the bad things that you see.

过去的过去 2024-10-14 23:29:50

有 2 个问题:

  1. str 设为 char[] 类型。 GCC 给出警告 foo.cpp:5: warning: deprecated conversion from string Constant to 'char*' 这表明这是一个有问题的行。

  2. 您的第二个 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("%s\n", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}

输出

one
two
three

There are 2 problems:

  1. Make str of type char[]. GCC gives the warning foo.cpp:5: warning: deprecated conversion from string constant to ‘char*’ which indicates this is a problematic line.

  2. Your second strtok() call should have NULL as its first argument. See the docs.

The resulting working code is:

#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("%s\n", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}

which outputs

one
two
three
他夏了夏天 2024-10-14 23:29:50

我不确定什么是“总线”错误,但如果您想继续解析相同的字符串,循环中 strtok() 的第一个参数应该为 NULL。

否则,您将继续从同一字符串的开头开始,顺便说一句,在第一次调用 strtok() 之后,该字符串已被修改。

I'm not sure what a "bus" error is, but the first argument to strtok() within the loop should be NULL if you want to continue parsing the same string.

Otherwise, you keep starting from the beginning of the same string, which has been modified, by the way, after the first call to strtok().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文