int printf(const char *format, ...);int fprintf(FILE *stream, const char *format, ...);
#include <stdarg.h>void va_start(va_list ap, last);type va_arg(va_list ap, type);void va_end(va_list ap);void va_copy(va_list dest, va_list src);
typedef struct {char *a0; /* pointer to first homed integer argument */int offset; /* byte offset of next parameter */} va_list;
//foo.c#include <stdarg.h>#include <stdio.h>voidfoo(char *fmt, ...){va_list ap;int d;char c, *s;va_start(ap, fmt);while (*fmt)switch (*fmt++) {case ‘s‘: /* string */s = va_arg(ap, char *);printf("string %s\n", s);break;case ‘d‘: /* int */d = va_arg(ap, int);printf("int %d\n", d);break;case ‘c‘: /* char *//* need a cast here since va_arg only/* need a cast here since va_arg onlytakes fully promoted types */c = (char) va_arg(ap, int);printf("char %c\n", c);break;}va_end(ap);}
//main.c#include <stdio.h>#include <stdarg.h>#include "foo.h"intmain(void){foo("%s %d %c %d %c", "Hello", 4, ‘x‘, 3, ‘y‘);return 0;}
windeal@ubuntu:~/Windeal/apue$ ./exestring Helloint 4char xint 3char ywindeal@ubuntu:~/Windeal/apue$
//foo.c#include <stdarg.h>#include <stdio.h>voidfoo(char *fmt, ...){va_list ap;int len = 0;char buf[64];va_start(ap, fmt);len = vsnprintf(buf, 128, fmt, ap);va_end(ap);int i = 0;for(i = 0; i < len; i++){putchar(buf[i]);}return ;}~
// main.c#include <stdio.h>#include <stdarg.h>#include "foo.h"intmain(void){foo("Test:%s %d %c %d %c\n", "Hello", 4, ‘x‘, 3, ‘y‘);return 0;}
windeal@ubuntu:~/Windeal/apue$ ./exeTest:Hello 4 x 3 y
va_start、va_arg、va_end、va_copy 可变参函数
原文地址:http://blog.csdn.net/windeal3203/article/details/39000901