printf函数:
1 #include <stdio.h> 2 #include <stdarg.h> 3 4 int myself_printf(char *format, ...) 5 { 6 va_list ap; 7 int n; 8 9 va_start(ap, format); 10 11 n = vprintf(format, ap); 12 13 va_end(ap); 14 15 return n; 16 } 17 18 int main(void) 19 { 20 myself_printf("test_num : %d ", 123); 21 }
运行结果:test_num : 123
error函数:
1 #include <stdio.h> 2 #include <stdarg.h> 3 4 int myself_error(char *format, ...) 5 { 6 va_list ap; 7 char *str; 8 int n; 9 10 va_start(ap, format); 11 12 fprintf(stderr, "Error: "); 13 vfprintf(stderr, format, ap); 14 15 va_end(ap); 16 17 return n; 18 } 19 20 int main(void) 21 { 22 myself_error("%s ", "main failure"); 23 }
运行结果:Error: main failure
函数:
1 #include <stdio.h> 2 #include <stdarg.h> 3 4 void foo(char *format, ...) 5 { 6 va_list ap; 7 char c, *s; 8 int d; 9 10 va_start(ap, format); 11 12 while (*format) { 13 switch (*format++) { 14 case 's': /* string */ 15 s = va_arg(ap, char *); 16 printf("string :%s ", s); 17 break; 18 case 'd': 19 d = va_arg(ap, int); 20 printf("int :%d ", d); 21 break; 22 case 'c': 23 c = (char) va_arg(ap, int); 24 printf("char :%c ", c); 25 break; 26 } 27 va_end(ap); 28 } 29 } 30 31 int main(void) 32 { 33 char c = 'b'; 34 foo("dc", "a", 1, c); 35 }
运行结果:
string :a
int :1
char :b
函数:
1 #include <stdio.h> 2 #include <stdarg.h> 3 4 void foo(int n, ...) 5 { 6 va_list ap; 7 int tmp, i; 8 9 va_start(ap, n); 10 11 for (i = 0; i < n; i++) { 12 tmp = va_arg(ap, int); 13 printf("tmp : %d ", tmp); 14 } 15 16 va_end(ap); 17 18 } 19 20 int main(void) 21 { 22 foo(4, "1", 2, 3, 4); 23 }
运行结果:
tmp : 1
tmp : 2
tmp : 3
tmp : 4
和上边的函数进行对比:
1 #include <stdio.h> 2 3 void foo(int n, ...) 4 { 5 int *temp = &n; 6 int i = 0; 7 8 temp++; 9 for (i = 0; i < n; i++) { 10 printf("temp : %d ", *temp); 11 temp++; 12 } 13 } 14 15 int main(void) 16 { 17 foo(4, 1, 2, 3, 4); 18 }
运行结果:
temp : 1
temp : 2
temp : 3
temp : 4
函数:
1 #include <stdio.h> 2 #include <stdarg.h> 3 4 void foo(char *format, ...) 5 { 6 va_list ap; 7 char *res; 8 9 va_start(ap, format); 10 11 res = va_arg(ap, char *); 12 printf("va_arg result : %s ", res); 13 printf("%s%s ", format, res); 14 15 va_end(ap); 16 } 17 18 int main(void) 19 { 20 foo("test : ", "foo"); 21 }
运行结果:
va_arg result : foo
test : foo
函数:
1 #include <stdio.h> 2 #include <stdarg.h> 3 4 void testFun(char *a, int b, char *c, ...) 5 { 6 va_list ap; 7 8 va_start(ap, c); 9 10 vsnprintf(a, b, c, ap); 11 printf("a : %s ", a); 12 13 va_end(ap); 14 } 15 16 int main(void) 17 { 18 char buf[128]; 19 testFun(buf, 4, "def"); 20 }
运行结果:a : def