C语言程序设计:前锋变量参数列表 [英] C Programming: Forward variable argument list

查看:155
本文介绍了C语言程序设计:前锋变量参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个接受可变数量的如printf参数,做一些东西的函数,然后通过该变量列表中的printf。我不知道如何做到这一点,因为它似乎将不得不他们推入堆栈。

I'm trying to write a function that accepts a variable number of parameters like printf, does some stuff, then passes the variable list to printf. I'm not sure how to do this, because it seems like it would have to push them onto the stack.

大约的东西像这样

http://pastie.org/694844

#include <stdio.h>
#include <stdarg.h>

void forward_args( const char *format , ... ){
  va_list arglist;
  printf( format, arglist );
}


int main (int argc, char const *argv[]){
  forward_args( "%s %s\n" , "hello" , "world" );  return 0;
}

任何想法?

推荐答案

不要将结果传递的printf 。它们传递到 vprintf vprintf 存在专门处理传入的va_list 参数。从Linux手册页:

Don't pass the results to printf. pass them to vprintf. vprintf specifically exists to handle passing in va_list arguments. From the Linux man page:

#include <stdio.h>

int printf(const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);

#include <stdarg.h>

int vprintf(const char *format, va_list ap);
int vfprintf(FILE *stream, const char *format, va_list ap);
int vsprintf(char *str, const char *format, va_list ap);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);

注意如何后者明确采取的va_list 参数,如你服用 ... 函数内声明的那些在参数列表中。所以,你的函数定义应该是这样的:

Notice how the latter explicitly take va_list arguments such as the ones you declare inside a function taking ... in the parameter list. So your function would be declared like this:

void forward_args( const char *format , ... ){
   va_list arglist;
   va_start( arglist, format );
   vprintf( format, arglist );
   va_end( arglist );
}

这篇关于C语言程序设计:前锋变量参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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