#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);
对于 last 的翻译似乎很是晦涩。看下面的具体应用:
void err_sys(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
.....
}
上面的程序片段中,err_sys() 是我们自定义的一个函数。在 err_sys() 中有参数 fmt,也就是 va_start() 中的 last 。这个参数位于可变参数列表(用 ... 表示)之前。也就是说,err_sys() 函数一开始明确就能知道参数。
#include <stdio.h>
#include <stdarg.h>
void foo(char *fmt, ...)
{
va_list ap;
int d;
char c, *s;
va_start(ap, fmt);
while (*fmt)
switch (*fmt++) {
case 's':
s = va_arg(ap, char *);
printf("string %s\n", s);
break;
case 'd':
d = va_arg(ap, int);
printf("int %d\n", d);
break;
case 'c':
c = (char) va_arg(ap, int);
printf("char %c\n", c);
break;
}
va_end(ap);
}
int main()
{
int val1 = 20;
char buf[20] = {"hello world"};
foo("kkkkkk%dxxxxxsxxxxx",val1,buf);
return 0;
}
beyes@linux-beyes:~/C> ./varg.exe
int 20
string hello world
varg.c: In function ‘foo’:
varg.c:14: error: expected specifier-qualifier-list before ‘kk’
varg.c: In function ‘foo’:
varg.c:14: warning: assignment makes pointer from integer without a cast
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) | Powered by Discuz! X3.2 |