2013-01-05 78 views
0

这里是我的代码:STDARG.H和焦炭paraments

void a_simple_func_with_variable_argument(int, ...); 
void a_simple_func_with_variable_argument(int start, ...) { 
    va_list pa; 
    char ch; 
    va_start(pa, start); 
    while(ch = va_arg(pa, char)) { 
    printf("%c, ", ch); 
    } 
    printf("End\n"); 
    va_end(pa); 
} 
... 
//call the func above in somewhere 
    a_simple_func_with_variable_argument(1, 'a', 'b', 'c', '\0'); 

它未能通过GCC编译后,你我错过了什么?

+0

你是否缺少'stdarg.h'?编译器告诉你缺少什么? –

+0

va_arg需要两个参数... –

+0

我的错误已经修复。 –

回答

3

您需要注意char;它会自动提升到int的可变参数函数。您将需要通过int作为第二个参数va_arg

+0

我讨厌这么愚蠢的我..谢谢你的家伙:) –

1

当我编译你的榜样(固定在va_arg(PA,焦炭)后),编译器(gcc 4.6)告诉我

a.c: In function 'a_simple_func_with_variable_argument':
a.c:8:14: warning: 'char' is promoted to 'int' when passed through '...' [enabled by default]
a.c:8:14: note: (so you should pass 'int' not 'char' to 'va_arg')
a.c:8:14: note: if this code is reached, the program will abort

所以毫不奇怪在这里。

+0

先到先得。不管怎样,谢谢你。 –

0
int func(char a, char b, char c) /* DEMONSTRATION that char on stack is promoted to int !!! 
            note: this promotion is NOT integer promotion of literals, but promotion during handling of the stack. don't confuse the two */ 
{ 
    const char *p = &a; 
    printf("a=%d\n" 
     "b=%d\n" 
     "c=%d\n", *p, p[-(int)sizeof(int)], p[-(int)sizeof(int) * 2]); // don't do this. might probably work on x86 with gcc (but again: don't do this) 
} 

该消息是va_arg(ap, char)va_arg(ap, short)是错误的。 改为使用va_arg(ap, int):它将处理int类型和“更小”类型(short,char)的参数。

又见http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html 引用:“小心这里避免可能由算术转换导致的问题char或短的第二个参数的va_arg使用必然是一个错误。这些类型始终弘扬高达签署一个int或unsigned int,并将float转换为double。“