简体   繁体   中英

Passing and using variable number of arguments to function in C

I don't understand why this doesn't print out "this is a test 42" like I'm expecting it to?

  1 #include <stdio.h>
  2 #include <stdarg.h>
  3 
  4 #define ME(x)   blah x
  5 
  6 void blah(const char *fmt, ...)
  7 {
  8         va_list arg;
  9 
 10         va_start(arg, fmt);
 11         printf(fmt, arg);
 12         va_end(arg);
 13 }
 14 
 15 int main()
 16 {
 17         ME(("this is a test %d\n", 42));
 18 
 19         return 0;
 20 }

Instead it's something like this:

$ gcc blah.c
$ ./a.out
this is a test 1606416656 

您想要调用vprintf()而不是printf()。

You should use va_arg to get the actual argument value. Va_start is only an initialization of the arg variable. Arg is actualy a pointer to the value on the stack, it's not the valut itself.

The following line gets the actual value:

int myvalue = va_arg(arg,int);

Notice that I get an int and not a short, since short's are automatically promoted to int by the C compiler.

EDIT: Uli's answer is also correct. If you want to pass multiple values to printf, you should call vprintf instead of printf (and then calling va_arg is not needed, since in this case you don't know the exact types of the arguments).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM