加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C使用va_list的函数可以多次使用它吗?

发布时间:2020-12-16 09:20:20 所属栏目:百科 来源:网络整理
导读:在下面的程序中,可变参数函数process_message通过va_list argp参数将其变量参数传递给print_message. argp又传递给vsnprintf,后者计算格式字符串的长度. 但是,如果将argp传递给另一个从print_message中调用的函数,例如vprintf(fmt,argp),它会产生无意义的输
在下面的程序中,可变参数函数process_message通过va_list argp参数将其变量参数传递给print_message. argp又传递给vsnprintf,后者计算格式字符串的长度.

但是,如果将argp传递给另一个从print_message中调用的函数,例如vprintf(fmt,argp),它会产生无意义的输出.使用va_list参数的函数是否可以多次使用它?

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

void process_message(const char *fmt,...);
void print_message(const char *fmt,va_list argp);

int main(void) {
  process_message("%s:%dn","test message",1);
  return 0;
}

void process_message(const char *fmt,...) {
  va_list argp;
  va_start(argp,fmt);
  print_message(fmt,argp);
  va_end(argp);
}

void print_message(const char *fmt,va_list argp) {
  /*Calculate and print the length of the format string*/
  int len = vsnprintf(NULL,fmt,argp);
  printf("Length of format string = %dn",len);
  /*Print the rendered format string - this produces a nonsense output
   *if argp was aleady passed to another function earlier */
  vprintf(fmt,argp);
}

解决方法

你可以使用 va_copy

The va_copy() macro copies the (previously initialized) variable argument list src to dest. The behavior is as if va_start() were applied to dest with the same last argument,followed by the same number of va_arg() invocations that was used to reach the current state of src.

你print_message()可能是:

void print_message(const char *fmt,va_list argp) {
  /*Calculate and print the length of the format string*/ 
  va_list argp_copy;
  va_copy(argp_copy,argp);
  int len = vsnprintf(NULL,argp_copy);
  va_end(argp_copy);

  printf("Length of format string = %dn",argp);
}

注意:

使用复制的va_list后不要忘记调用va_end.

C11:

Each invocation of the va_start and va_copy macros shall be matched by a corresponding invocation of the va_end macro in the same function.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读