本文介绍了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 编程:前向变量参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:16