Passing variable number of arguments around

前端 未结 11 738
我寻月下人不归
我寻月下人不归 2020-11-22 07:16

Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing a

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 07:30

    Though you can solve passing the formatter by storing it in local buffer first, but that needs stack and can sometime be issue to deal with. I tried following and it seems to work fine.

    #include 
    #include 
    
    void print(char const* fmt, ...)
    {
        va_list arg;
        va_start(arg, fmt);
        vprintf(fmt, arg);
        va_end(arg);
    }
    
    void printFormatted(char const* fmt, va_list arg)
    {
        vprintf(fmt, arg);
    }
    
    void showLog(int mdl, char const* type, ...)
    {
        print("\nMDL: %d, TYPE: %s", mdl, type);
    
        va_list arg;
        va_start(arg, type);
        char const* fmt = va_arg(arg, char const*);
        printFormatted(fmt, arg);
        va_end(arg);
    }
    
    int main() 
    {
        int x = 3, y = 6;
        showLog(1, "INF, ", "Value = %d, %d Looks Good! %s", x, y, "Infact Awesome!!");
        showLog(1, "ERR");
    }
    

    Hope this helps.

提交回复
热议问题