Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Passing variable number of arguments from one function to another

So, here's a small problem I'm facing right now -> I'm trying to write a function that will accept a char* message and a variable number of arguments. My function will modify the message a little, and then It'll call printf with the message and given parameters. Essentialy, I'm trying to write something like that:

void modifyAndPrintMessage(char* message,...){
    char* newMessage; //copy message.
    //Here I'm modifying the newMessage to be printed,and then I'd like to print it. 
    //passed args won't be changed in any way.

    printf(newMessage,...); //Of course, this won't work. Any ideas?
    fflush(stdout);

}

So, anybody knows what should I do to make it happen? I'd be most grateful for any help :)

like image 705
JJS Avatar asked Apr 05 '13 14:04

JJS


People also ask

What mechanism is used in C for functions with variable number of arguments?

Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.

What is variable number of arguments in C?

To call a function with a variable number of arguments, simply specify any number of arguments in the function call. An example is the printf function from the C run-time library. The function call must include one argument for each type name declared in the parameter list or the list of argument types.

What is __ Va_args __ in C?

To use variadic macros, the ellipsis may be specified as the final formal argument in a macro definition, and the replacement identifier __VA_ARGS__ may be used in the definition to insert the extra arguments. __VA_ARGS__ is replaced by all of the arguments that match the ellipsis, including commas between them.


2 Answers

You want to use varargs...

void modifyAndPrintMessage( char* message, ... )
{
    // do somehthing custom

    va_list args;
    va_start( args, message );

    vprintf( newMessage, args );

    va_end( args );
}
like image 107
K Scott Piel Avatar answered Oct 12 '22 23:10

K Scott Piel


void modifyAndPrintMessage(char* message,...)
{   char newMessage[1024]; // **Make sure the buffer is large enough**
    va_list args;
    va_start(args, message);
    vsnprintf(newMessage, message, args);
    printf(newMessage);
    fflush(stdout);
}
like image 31
Edward Clements Avatar answered Oct 12 '22 23:10

Edward Clements