call printf using va

void TestPrint(char* format, ...)
{
    va_list argList;

    va_start(argList, format);
    printf(format, argList);
    va_end(argList);
}


int main()
{
    TestPrint("Test print %s %dn", "string", 55);
    return 0;
}

I neet to get:

Test print string 55

Actually, I get garbage output. What is wrong in this code?


改用vprintf()


Instead of printf, I recommend you try vprintf instead, which was created for this specific purpose:

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

void errmsg( const char* format, ... )
{
  va_list arglist;

  printf( "Error: " );
  va_start( arglist, format );
  vprintf( format, arglist );
  va_end( arglist );
}

int main( void )
{
  errmsg( "%s %d %s", "Failed", 100, "times" );
  return EXIT_SUCCESS;
}

Source: http://www.qnx.com/developers/docs/6.5.0/index.jsp?topic=/com.qnx.doc.neutrino_lib_ref/v/vprintf.html


As others have pointed out already: In this case you should use vprintf instead.

But if you really want to wrap printf , or want to wrap a function that does not have a v... version, you can do that in GCC using the non-standard __builtin_apply feature:

int myfunction(char *fmt, ...)
{
    void *arg = __builtin_apply_args();
    void *ret = __builtin_apply((void*)printf, arg, 100);
    __builtin_return(ret);
}

The last argument to __builtin_apply is the max. total size of the arguments in bytes. Make sure that you use a value here that is large enough.

链接地址: http://www.djcxy.com/p/72148.html

上一篇: C文本处理:输出大小错误

下一篇: 使用va调用printf