gpt4 book ai didi

c - va_arg(argp, float) 正在崩溃

转载 作者:行者123 更新时间:2023-12-04 05:21:41 27 4
gpt4 key购买 nike

我正在尝试编写自定义 printf 函数。

void debug_print(const char *fmt, ...)
{
const char *p;
va_list argp;
int i;
double f;
char *s;
char fmtbuf[80];

va_start(argp, fmt);

for(p = fmt; *p != '\0'; p++)
{
if(*p != '%')
{
uart_putchar(*p);
continue;
}

switch(*++p)
{
case 'c':
...
break;

case 'f':
f = va_arg(argp, float); // ??????
s = dtostrf(f, 10, 6, fmtbuf);
uart_puts(s);
break;

...
// then in the main part of the program
debug_print("%f", 123.456);

当程序遇到 f = va_arg(argp, float) 时,它永远不会从该行返回。如果我将其更改为 f = va_arg(argp, double) 它返回 0。

在设备(ATMega328P)和 Atmel Studio 6 模拟器上都试过,结果相同。

听起来像是与链接器选项有关?

更新:

现在只需要找出 va_arg(argp, double) 返回 0 的原因。

最佳答案

当您通过 float在变量参数列表中,它被隐式提升为 double由编译器。所以,你必须使用 va_arg(argp, double)从变量参数列表中获取它。

当您尝试将参数作为 float 获取时,那么

type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions) [and] the behavior is undefined



(标准 §7.16.1.1, va_arg 宏。根据 §6.2.7, floatdouble 不兼容。)

关于c - va_arg(argp, float) 正在崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13627289/

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