Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call printf using va_list

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?

like image 788
Alex F Avatar asked May 12 '11 11:05

Alex F


People also ask

What does Va_list mean?

va_list is a complete object type suitable for holding the information needed by the macros va_start, va_copy, va_arg, and va_end. If a va_list instance is created, passed to another function, and used via va_arg in that function, then any subsequent use in the calling function should be preceded by a call to va_end.

What is vsprintf?

The vsprintf is defined in the stdio. h header file. It uses a format string and corresponding arguments to generate a string stored in the provided destination string.

What is Vfprintf in C?

The C library function int vfprintf(FILE *stream, const char *format, va_list arg) sends formatted output to a stream using an argument list passed to it.


2 Answers

Use vprintf() instead.

like image 122
Oliver Charlesworth Avatar answered Sep 20 '22 08:09

Oliver Charlesworth


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

like image 36
onteria_ Avatar answered Sep 18 '22 08:09

onteria_