简体   繁体   English

C,处理变量参数函数

[英]C, Dealing with variable argument functions

Let's say I want to do something like this 假设我想做这样的事情

void my_printf(char *fmt,...) {
 char buf[big enough];
 sprintf(buf,fmt,...);  
}

What is the proper way of passing the variable number of arguments directly to a function with accepts variable arguments? 将可变数量的参数直接传递给具有接受变量参数的函数的正确方法是什么?

sprintf has a va_list form called vsprintf . sprintf有一个名为vsprintfva_list表单。 Pass the va_list you construct locally to it as the last argument. 将您在本地构造的va_list作为最后一个参数传递给它。

void my_printf(char *fmt,...) {
 va_list ap;
 va_start(ap, fmt);

 char buf[big enough];
 vsprintf(buf,fmt,ap);

 va_end(ap);
}

I'm not sure how useful this code will be, as it is C++, but it shows how to check, using a Win32 specific function vsnprintf(), that the buffer allocated is big enough and if not allocates a bigger one. 我不确定这段代码有多么有用,因为它是C ++,但是它展示了如何使用Win32特定函数vsnprintf()来检查分配的缓冲区是否足够大,如果没有分配更大的缓冲区。 And it returns a std::string, so you would have to use malloc/realloc to handle that. 它返回一个std :: string,所以你必须使用malloc / realloc来处理它。 But what the hell: 但到底是什么:

string Format( const char * fmt, ... ) {
    const int BUFSIZE = 1024;
    int size = BUFSIZE, rv = -1;
    vector <char> buf( size );
    do {
        va_list valist;
        va_start(valist, fmt );
        // if vsnprintf() returns < 0, the buffer wasn't big enough
        // so increase buffer size and try again
        rv = _vsnprintf( &buf[0], size, fmt, valist );
        va_end( valist );
        size *= 2;
        buf.resize( size );
    }
    while( rv < 0 );
    return string( &buf[0] );
}

You can us the vsprintf style functions to get printf style printing for your variable length parameter. 您可以使用vsprintf样式函数来为您的可变长度参数获取printf样式打印。 However there is no requrement to do so. 但是没有这样做的要求。 You can if you choose write your function to keep accepting parameters until it encounters a null pointer. 如果您选择编写函数以继续接受参数,直到遇到空指针,则可以。

 va_list ap;
char *param;
va_start(ap,fmt);
param = va_arg(ap,char*);
while(param)
{
do something...
param = va_arg(ap,char*);
}

or you can have the number of parameters as the first param to your function 或者你可以将参数的数量作为你的函数的第一个参数

void my_printf(int param_num,...)
{
 va_list ap;
char *param;
va_start(ap,fmt);
while(param_num)
{
do something...
param = va_arg(ap,char*);
param_num--;
}

}

Its really up to you, the possibilities are limitless. 它真的取决于你,可能性是无限的。 I think the only real requirement to the ellipses is that it has at least one parameter before the ellipses. 我认为省略号的唯一真正要求是它在省略号之前至少有一个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM