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,451
  • 8
  • 37
  • 64
  • 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 - on strike Aug 05 '12 at 05:55

4 Answers4

7

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

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
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,729
  • 5
  • 57
  • 110
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,354
  • 4
  • 36
  • 61
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
  • 7,258
  • 1
  • 32
  • 34