gpt4 book ai didi

c - va_arg 不适用于 double

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:23 24 4
gpt4 key购买 nike

我有一个函数,它接受可变数量的参数,然后将每个参数传递给一个函数,具体取决于其他因素。这对大多数类型都适用,无论它们是否是指针

func = (fmtfunc_t)dictobj(deflt, tok);
dat = func(va_arg(lst, void *));

其中 fmtfunc_t 定义为

typedef char * (*fmtfunc_t)(void *);

此方法适用于例如以下函数

char *examp1(int i) {
// i points to the correct integer value
}
char *examp2(char *s) {
// s points to the correct string value
}

但是,当参数是 double

时它不起作用
char *examp3(double d) {
// d is 0
}

我知道 issues使用 va_arg 和双重提升,但我不认为这是我问题的根源。我这样调用函数

func(23.4);

如您所见,参数是一个 double 文字,所以我认为我不应该关心提升问题。

为什么 va_argdouble 返回不正确的值,但对任何其他类型都没有?我是否遇到了某种未定义的行为并且幸运地使用了 double 以外的类型?

最佳答案

正如@RaymondChen、@Olaf 和@FUZxxl 在评论中指出的那样,问题在于,通过使用与声明不兼容的类型的参数调用函数

char *examp(int i);

fmtfunt_t func = examp;
func(va_arg(lst, void *)); //called with an argument of void*, but the parameter is of type int

我导致了未定义的行为。我通过获取参数作为它们适当的类型来解决这个问题

double arg = va_arg(lst, double);

而不是尝试使用 void * 作为包罗万象。

关于c - va_arg 不适用于 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33638661/

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