2010-10-04 8 views

Répondre

2
so ross$ expand < variadic.c && cc -Wall -Wextra variadic.c 
#include <stdio.h> 
#include <stdarg.h> 

void f(int, ...); 
struct x { int a, b; } y = { 5, 6 }; 

int main(void) { 
    float q = 9.4; 
    f(0, 1.234, &q, "how now", 123, &y); 
    return 0; 
} 

void f(int nothing, ...) { 
    va_list ap; 

    va_start(ap, nothing); 
    double f = va_arg(ap, double); 
    float *f2 = va_arg(ap, float *); 
    char *s = va_arg(ap, char *); 
    int i = va_arg(ap, int); 
    struct x *sx = va_arg(ap, struct x *); 
    va_end(ap); 

    printf("%5.3f %3.1f %s %d %d/%d\n", f, *f2, s, i, sx->a, sx->b); 
} 
so ross$ ./a.out 
1.234 9.4 how now 123 5/6 
3

vous, regardez les usages communs de printf:

printf("Error %d: %s", errNum, errTxt); 
+0

Pouvez-vous donner un exemple, sauf printf – Shweta

+0

@Shweta: scanf serait l'autre évidente. Ceux-ci (avec des variantes comme sprintf, fscanf, etc.) sont presque les seules fonctions variadiques en usage très répandu. –

0

Voici un exemple sans printf (ancienne version: http://codepad.org/vnjFj7Uh)

#include <stdarg.h> 
#include <stdio.h> 

/* return the maximum of n values. if n < 1 returns 0 */ 
/* lying to the compiler is not supported in this version, eg:   ** 
** va_max(4, 8, 8, 8, 8, 8, 8, 8, 8)        ** 
** or                 ** 
** va_max(4, 2, 2)             ** 
/* is a bad way to call the function (and invokes Undefined Behaviour) */ 
int va_max(int n, ...) { 
    int res; 
    va_list arg; 

    if (n < 1) return 0; 

    va_start(arg, n); 
    n--; 
    res = va_arg(arg, int); 
    while (n--) { 
    int cur = va_arg(arg, int); 
    if (cur > res) res = cur; 
    } 
    return res; 
} 

int main(void) { 
    int test6 = va_max(6, 1, 2, 3, 4, 5, 6); 
    int test3 = va_max(3, 56, 34, 12); 
    if (test6 == 6) puts("6"); 
    if (test3 == 56) puts("56"); 
    return 0; 
} 
+0

Juste un détail technique ... Je vois quelques appels 'printf' dedans ... ;-) –

+0

La fonction principale était une après pensée ... mais plus printfs maintenant (sauf sur le codepad) – pmg

0

J'ai fait une fonction pour décompresser des données binaires en utilisant une fonction varadic, il faut différents types basés sur ce que vous voulez "codé/décodé".

Vous souhaitez l'utiliser comme:

uint32_t a; 
uint16_t b; 
uint16_t c; 
uint8_t *buf = ....; 

depickle(buf,"sis",&a,&b,&c); 

où l « » attend un uint16_t * et décode 2 octets de buf dans a aussi peu endian, « i » dit décoder 4 octets comme peu endian dans 'b'

Ou à par exemple décoder 4 octets comme grand-boutiste dans un uint32_t:

uint32_t a; 
uint8_t buf[] = {0x12,0x34,0x56,0x78}; 
depickle(buf,"I",&a); 

Il y a encore une première version autour here.

Questions connexes