Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

forward args of variadic function in C

I want to forward args of variadic function, I have already find the some topic.

When I start to practice, I found a problem.

#include <stdio.h>
#include <stdarg.h>
void fun1(const char *msg, ...) // try to forward printf
{
    va_list arg_list;
    va_start(arg_list, msg);
    vprintf(msg, arg_list);
    va_end(arg_list);
}

void fun2(const char *msg, ...) // try to forward fun1
{
    va_list arg_list;
    va_start(arg_list, msg);
    fun1(msg, arg_list);
    va_end(arg_list);
}

int main()
{
    fun1("this is int %d, float %f\n", 1, 2.3);
    fun2("this is int %d, float %f\n", 1, 2.3);
    return 0;
}

I compile code with gcc main.c and the output shown that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this is int 1, float 2.300000
this is int 6684168, float 2.300000

I can not understand why the fun2 not forward the args of fun1 correctly.
Why the int 1 goes to another number but 2.3 still good.
How can I modify my code to implement the forward?

Thanks for your time.

>Solution :

fun1 needs a list of arguments to match its format, but when call it from fun2 you give it a va_list. To call it that way you need to rewrite it to take a va_list rather than a ...:

void fun1(const char *fmt, va_list args) {
    vfprintf(fmt, args);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading