gpt4 book ai didi

c++ - va_arg 给出运行时错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:35 31 4
gpt4 key购买 nike

我正在尝试编写一个带有格式字符串和一些可变数字参数的小函数。格式字符串采用表示不同数字类型的各种字符(c 表示 char,i 表示 int,d 表示 double 等),然后字符串中的每个字符采用该类型的数字。然后它返回所有这些数字的总和。示例调用如下所示:

addEm("cid", 'A', 4, 5.0)

这将返回 74,在计算中使用 'A' 的 ascii 码

函数如下所示:

double addEm(char *format, ...) {
va_list params;
va_start(params,format);
double ret=0;
while(*format) {
switch(*format++) {
case 'c':
ret+=(double)(va_arg(params, char));
break;
case 'd':
ret+=va_arg(params, double);
break;
case 'i':
ret+=(double)(va_arg(params, int));
break;
case 's':
ret+=(double)(va_arg(params, short));
break;
case 'f':
ret+=(double)(va_arg(params, float));
break;
}
}
va_end(params);
return ret;
}

但是,当我运行如上所示的调用时,它会产生错误,而且我似乎无法弄清楚原因。谁能看到我做错了什么?谢谢!

最佳答案

试试这个:

double addEm(char *format, ...) {
va_list params;
va_start(params,format);
double ret=0;
while(*format) {
switch(*format++) {
case 'c':
ret+=(double)(va_arg(params, int));
break;
case 'd':
ret+=va_arg(params, double);
break;
case 'i':
ret+=(double)(va_arg(params, int));
break;
case 's':
ret+=(double)(va_arg(params, int));
break;
case 'f':
ret+=(double)(va_arg(params, double));
break;
}
}
va_end(params);
return ret;
}

以下是一些可能有用的 gcc 警告:

t038.c:12:19: warning: ‘char’ is promoted to ‘int’ when passed through ‘...’ [enabled by default]
t038.c:12:19: note: (so you should pass ‘int’ not ‘char’ to ‘va_arg’)
t038.c:12:19: note: if this code is reached, the program will abort
t038.c:21:19: warning: ‘short int’ is promoted to ‘int’ when passed through ‘...’ [enabled by default]
t038.c:21:19: note: if this code is reached, the program will abort
t038.c:24:19: warning: ‘float’ is promoted to ‘double’ when passed through ‘...’ [enabled by default]
t038.c:24:19: note: if this code is reached, the program will abort

关于c++ - va_arg 给出运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22550154/

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