c - 为什么 strtod 不能以正确的方式工作?

标签 c string

我正在使用 GNU GCC 编译器在代码块编辑器中编码。我尝试使用以下原型(prototype)的函数 strtod:

double strtod(const char *a, char **b);

如果我使用下面的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
    char *a;
    a="99.5HELLO";
    char *b;
    printf("%.1lf\n%s", strtod(a, &b), b);
    return 0;
}

我希望控制台终端在运行代码后呈现如下内容:

99.5
HELLO

但我实际得到的是一些奇怪的东西:

99.5
@

这是怎么回事?我哪里做错了?

最佳答案

子表达式的求值顺序是未指定的,因此最后一个函数参数可能首先被求值,您最终会读取未初始化的值 b,这是未定义的行为。

订购评估:

const char *a = "99.5HELLO";
char *b;
double d = strtod(a, &b);

printf("%.1f\n%s", d, b);

关于c - 为什么 strtod 不能以正确的方式工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34239453/

相关文章:

javascript - 从对象数组创建字符串的最简单方法

python - OpenMP 和 Cython 缺乏加速和错误结果

c - 数组声明 : C Segmentation fault

c - 链表未定义行为

c++ - 在嵌入式系统中使用 xml 作为数据库有什么好处?

C 编译程序崩溃

regex - 使用 Go 从字符串中删除所有文章和其他字符串?

python - 在python中如何处理域名中的其他编码

sql - 将表列合并为单个字符串(无 UDF)

string - 在超过一百万个字符串的列表中按相反顺序排列字符串对?