传递和使用C中的可变数量的参数功能 [英] Passing and using variable number of arguments to function in C

查看:80
本文介绍了传递和使用C中的可变数量的参数功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这不能打印出这是一个测试42像我就期待?

  1的#include<&stdio.h中GT;
  2#包括LT&;&STDARG.H GT;
  3
  4#定义ME(X)等等点¯x
  五
  6无效等等(为const char * FMT,...)
  7 {
  8 va_list的ARG;
  9
 10的va_start(阿根廷,FMT);
 11的printf(FMT,ARG);
 12 va_end用来(ARG);
 13}
 14
 15 INT的main()
 16 {
 17 ME((这是一个测试%d个\\ N,42));
 18
 19返回0;
 20}

相反,它是这样的:

  $ GCC blah.c
$ ./a.out
这是一个测试1606416656


解决方案

您想打电话给代替了printf vprintf()()

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 

解决方案

You want to call vprintf() instead of printf().

这篇关于传递和使用C中的可变数量的参数功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆