Odd behavior of a function with a variable number of parameters in C

I have the following C function with a variable number of arguments, which should search char* wordthrough a hash table and write trueeither falsein a file, which, if specified, is the second parameter; otherwise it is stdout.

It works fine if I specify a file name, the problem is that I do not (for example, find("foo")). In this case, it writes the result to a file with the name fooinstead stdout.

What is the reason?

void find(char* word, ...)
{
va_list list;
char *fname = NULL;
va_start(list, word);
FILE* f;
fname = strdup(va_arg(list, char*));
va_end(list);
if (<condition>)    // condition suited for the case in which the file name is received 
    f = fopen(fname, "a");
else
    f = stdout;
if (member(word))
    fprintf(f, "True\n");
else
    fprintf(f, "False\n");
}

Instead, <condition>I tried fname != NULLand strlen(fname) > 0, but they do not apply, and he continues to see fnamehow word, when fnamenot specified.

Thanks so much for any help you can provide.

+5
1

va_* :

( ), .

, - (, NULL):

find (word, NULL);
find (word, filename, NULL);

:

find (1, word);
find (2, word, filename);
+6

All Articles