当使用strtok时,标准C函数atof返回分段错误

10a*_*nts 1 c strtok atof

我有使用atof和strtok的问题.

#include<stdio.h> // printf
#include<stdlib.h> // atof
#include<string.h> // strtok

int main()
{
  char buf[256]="123.0 223.2 2314.2";
  char* tp;

  printf("buf : %s\n", buf);
  tp = strtok(buf," ");
  printf("tp : %g ", atof(tp));
  while (tp!=NULL) {
    tp = strtok(NULL," ");
    printf("%g ", atof(tp));
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我可以编译上面的代码,它不会返回任何错误或警告消息.但是当我执行"a.out"时,它会返回如下所示的分段错误.

78746 Segmentation fault: 11  ./a.out
Run Code Online (Sandbox Code Playgroud)

我不知道是什么问题.正如我所见,上面的代码不会复合语法错误.

Kla*_*äck 10

tp变为null时,你atof就可以了!

像这样重写你的循环:

int main()
{
  char buf[256]="123.0 223.2 2314.2";
  char* tp;

  printf("buf : %s\n", buf);
  tp = strtok(buf," ");
  printf("tp :");
  while (tp!=NULL) {
    printf("%g ", atof(tp));
    tp = strtok(NULL," ");
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)