Matthew Hoggan Matthew Hoggan - 10 months ago 57
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.

ncurses_add_line(const char *fmt, ...)
if (ncurses_window) {
va_list args;
va_start(args, fmt);
printw(fmt, args);

When I call this function I get gibberish in the variadic print out of my function. If I call
directly it all works. For example, if I call
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
but this is not the case for

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 Source

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.