将 va_list 传递给其他函数 [英] Passing va_list to other functions

查看:32
本文介绍了将 va_list 传递给其他函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将变量参数传递给 C 中的其他函数,但它在不同的运行时环境以及在同一环境中的不同运行中产生不一致的结果:

I have been trying to pass variable arguments to other function in C but it is producing inconsistent result in different runtime environment as well as in different runs in same environment:

int main() 
{ 
    int result = myprintf("Something \n %d", 9); 
    return result;
}

int myprintf(const char *format, ...){
    printf("Something \n %d", 9); 
    printf("\n");
    va_list args;        
    va_start(args, format);    
    int result = printf(format,args);
    printf("\n");
    va_end(args);
    return result;
} 

产生的结果是:

WWW.FIRMCODES.COM 
 9
WWW.FIRMCODES.COM 
 438656664

我找不到438656664"的原因.

I could not find the reason for "438656664".

推荐答案

不能将可变参数传递给可变参数函数.相反,您必须调用一个以 va_list 作为参数的函数.标准库提供了采用 va_listprintfscanf 的变体;他们的名字有前缀v.

You cannot pass the variadic arguments to a variadic function. Instead, you must call a function that takes a va_list as argument. The standard library provides variants of printf and scanf that take a va_list; their names have the prefix v.

您的示例应如下所示:

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

int printfln(const char *format, ...)
{
    int result;
    va_list args;

    va_start(args, format);
    result = vprintf(format, args);
    printf("\n");
    va_end(args);

    return result;
}

int main()
{
    int result = printfln("Something \n %d", 9);

    printf("(%d)\n", result);

    return 0;
}

有一些问题,例如当你想调用两个 v... 函数来打印到屏幕和一个日志文件时:v...函数可能会耗尽 va_list,所以如果你的代码应该是可移植的,你必须向每个调用传递一个新的.

There are some gotchas, for example when you want to call two v... function for printing to the screen and a log file: The v... function may exhaust the va_list, so you must pass in a fresh one to each call if your code should be portable.

这篇关于将 va_list 传递给其他函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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