0

What's wrong with the follwing code? How can we make the function print() to work as printf?

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

void print(char *format,...)
{
    va_list args;
    va_start(args,format);
    printf(format,args);
}

int main() {
   print("%d %s",5,"le");
}
user1232138
  • 5,301
  • 5
  • 35
  • 61
  • possible duplicate of [what's the difference between the printf and vprintf function families, and when should I use one over the other?](http://stackoverflow.com/questions/1485805/whats-the-difference-between-the-printf-and-vprintf-function-families-and-when) – Praetorian May 21 '12 at 16:07
  • possible duplicate of [call printf using va_list](http://stackoverflow.com/questions/5977326/call-printf-using-va-list) – Cody Gray Aug 05 '12 at 05:55

4 Answers4

7

If you need to pass varargs, then use vprintf instead.

Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
3

You probably need to look at vprintf. That function (and the related ones) allow you to pass along a variable argument list, and they handle the formatting.

Mark Wilkins
  • 40,032
  • 5
  • 54
  • 108
3

You need vprintf there. Take a look this question, it has a similiar problem: what's the difference between the printf and vprintf function families, and when should I use one over the other?

Community
  • 1
  • 1
kratenko
  • 7,032
  • 4
  • 33
  • 58
1

First of all there is a va_end() call missing which is mandatory if using va_start().

And you cannot use printf() if you want to use a va_list as argument. Take a look at vprintf().

example:

void print(char *format,...)
{
    va_list args;
    va_start(args,format);
    vprintf(format,args);
    va_end(args);
}
dwalter
  • 6,940
  • 1
  • 29
  • 34