gpt4 book ai didi

c - 标准 C 函数 atof 在与 strtok 一起使用时返回段错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:15:13 25 4
gpt4 key购买 nike

我在使用 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;
}

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

78746 Segmentation fault: 11  ./a.out

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

最佳答案

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;
}

关于c - 标准 C 函数 atof 在与 strtok 一起使用时返回段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20351616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com