va_arg给出运行时错误

时间:2014-03-21 04:25:55

标签: c++ c variadic-functions

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

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

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

该功能如下所示:

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

但是当我进行如上所述的呼叫时会产生错误,而我似乎无法找出原因。谁能看到我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个:

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