Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

c - How do I fill a va_list

If I have a va_list I know how to extract all its elements:

void printInts(int n,...)
{
    va_list va;
    va_start(va, n);
    for(unsigned int i=0; i<n; i++)
    {
        int arg=va_arg(va, int);
        printf("%d",arg);
    }
    va_end(va);
} 

So when I call printInts(3,1,2,3) the va_list get filled of all the parameters.
But how do I manually fill a va_list without using va_start? I mean that I want something like:

va_list va;
push_arg(va, int, 5); // And so on until I fill all parameters
...

I need this because there is a function that accept a va_list as argument, and I don't know how to fill that va_list of all its parameters.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's no ability to fill a va_list explicitly.

You should write a wrapper function. Say you need to call your function foo, instead of manually filling in a va_list, you define a new function like so:

void call_foo(int arg1, ...)
{
   va_list ap;
   va_start(ap, arg1);
   foo(arg1, ap);
   va_end(ap);
}

Now you can call foo, which takes a va_list, however you like, by doing e.g. call_foo(1,2,3,4);, call_foo(1, 1, "Hello"); etc.

This will only allow you to specify the arguments at compile time, you can't build the arguments at runtime.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...