2013-01-05 129 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。「