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 :)
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.
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.
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.
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 );
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With