call printf using va_list

做~自己de王妃 提交于 2019-11-26 05:29:42

问题


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

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


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

I need to get:

Test print string 55

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


回答1:


Use vprintf() instead.




回答2:


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




回答3:


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.




回答4:


This is not how you use printf(). If you want to use va_lists, use vprintf() instead. Look here fore reference.



来源:https://stackoverflow.com/questions/5977326/call-printf-using-va-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!