Matthew Hoggan Matthew Hoggan - 15 days ago 5
C Question

Forward Variadic Argument List to ncurses printw function in c

This has been asked in several different flavors. Yet I can still not get it to work. Here is my function definition.

void
ncurses_add_line(const char *fmt, ...)
{
if (ncurses_window) {
va_list args;
va_start(args, fmt);
printw(fmt, args);
printw("\n");
va_end(args);
}
}


When I call this function I get gibberish in the variadic print out of my function. If I call
printw
directly it all works. For example, if I call
ncurses_add_line
like
ncurses_add_line("Hello %d", var)
I get a value not store in var. However, if I call
printw("Hello %d", var)
, I see the value of var displayed next to "Hello" as in, if var == 1 then "Hello 1" is printed with
printw
but this is not the case for
ncurses_add_line
.

What do I need to change?

My reason for wrapping this up is because I don't want to include in my header file, only in my c file.

Answer

Try vwprintw instead of printw. vwprintw takes a va_list as its argument.

The idiom you're trying to use -- passing a va_list to a function that takes a variable number of arguments -- won't work. One solution is to find a variant of the function that will work (in this case, vwprintw). An alternative is to "flatten" the va_list: in this case, you could use vsprintf to create a formatted string, and then pass that into curses.

Comments