Create va_list dynamically

后端 未结 7 727
一个人的身影
一个人的身影 2020-12-06 01:08

I have a function

void foo(int cnt, va_list ap);

I need to use it, but requirement is quite strict, number of va_list vary an

相关标签:
7条回答
  • 2020-12-06 01:48

    What you are trying to use is alloca. A va_list object can not store variables, the function call stores them, and you can only access it via va_list. These variables are only valid during the call, and they get ovverwriten afterwards.

    THIS WILL NOT WORK:

    va_list func(int dummy, ...)
    {
       va_list result;
       va_start(result, dummy);
       return result;
    }
    

    To allocate memory on the stack, without having to write a variadic functions use alloca. It works more or less like malloc, but you don't have to call free, it automagically frees itself when you leave the scope.

    int * local = (int *) alloca(3 * sizeof(int));
    local[0] = 10;
    local[1] = 20;
    local[2] = 30;
    

    It's fundamentally the same as writing

    int local[3];
    local[0] = 10;
    local[1] = 20;
    local[2] = 30;
    

    But with alloca 3 does not need to be a constant. Again you can only use it inside the enclosing scope, so do not return it from the function.

    if what you want from a va_list is the multiple types in one list consider writing a union like this:

    union variant
    {
        int          i;
        unsigned int u;
        float        f;
        double       d;
        const char * s;
        void *       v;
    };
    
    0 讨论(0)
提交回复
热议问题