简体   繁体   English

C变量参数传递给函数

[英]C Variable arguments passing to function

I have a module with aa variable number of parameters: 我有一个带有可变数量参数的模块:

int myprintf( const char *format, ...  ){

}

I want to declare a local char array, pass the "myprint" parameters to sprintf() so that sprintf() converts the parameters to a character array then I can do something with that character array. 我想声明一个本地char数组,将“ myprint”参数传递给sprintf(),以便sprintf()将参数转换为字符数组,然后可以对该字符数组执行某些操作。 By doing this, I do not have to re-invent the internals of sprintf. 这样,我不必重新发明sprintf的内部结构。

In theory: 理论上:

int myprintf( const char *format, ...  )

{
    char buf[ 512 ];

    sprintf( buf, format, ... );

  // now do something with buf

}

I am sure va_start( a, b) , va_arg( c, d ) will have something to do with it; 我确信va_start( a, b)va_arg( c, d )与它有关; but va_arg seems to need parse the original argument list. 但是va_arg似乎需要解析原始参数列表。

Any suggestions? 有什么建议么?

To elaborate on what Chris said, something like: 要详细说明克里斯的话,例如:

int vmyprintf(const char* format, va_list args)
{
        char buf[512];

        vsnprintf(buf, sizeof(buf), fmt, args);
        // now do something with buf 
}

int myprintf(const char *format, ...)
{
        va_list args;
        int ret;

        va_start(args, format);
        ret = vmyprintf(format, args);
        va_end(args);
        return ret;
}

You are probably looking for something like that: 您可能正在寻找类似的东西:

void myprintf( const char *format, ...  )
{
    char buf[ 512 ];

    va_list vl;
    va_start (vl, format);
    vsnprintf(buf, 511, format, vl);
    va_end(vl);

    // now do something with buf
}

Some other information is available in my answer here 我的答案在这里有一些其他信息

Of course the above answer leave many issues open, for instance how will we handle buffer overflows or such. 当然,以上答案使许多问题悬而未决,例如,我们将如何处理缓冲区溢出等问题。 But this is another story. 但这是另一个故事。

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

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