[英]Odd behavior of function with variable number of parameters in C
I have the following C function with a variable number of arguments, which is supposed to search the char* word
through a hashtable and write true
or false
in a file which, if specified, is the second parameter; 我有以下带有可变数量参数的C函数,它应该通过哈希表搜索
char* word
,并在文件中写入true
或false
,如果指定,则为第二个参数; otherwise, it is stdout
. 否则,它是
stdout
。
It works fine if I specify the name of the file, the problem is when I don't (eg find("foo")
). 如果我指定文件的名称,它的工作正常,问题是当我不指定时(例如
find("foo")
)。 In this case it writes the result in a file named foo
instead of stdout
. 在这种情况下,它将结果写入名为
foo
的文件而不是stdout
。
What is the cause? 原因是什么?
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");
}
In place of <condition>
I've tried fname != NULL
and strlen(fname) > 0
but those don't apply and it keeps seeing fname
as word
when fname
is not specified. 在地方的
<condition>
我已经试过fname != NULL
和strlen(fname) > 0
,但那些不适用,它保持看到fname
的word
时fname
未指定。
Thank you very much for any help you can provide. 非常感谢您提供的任何帮助。
From va_*
's man page: 来自
va_*
的手册页:
If there is no next argument , or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur .
如果没有下一个参数 ,或者type与实际的下一个参数的类型不兼容(根据默认参数提升而提升), 则会发生随机错误 。
If you want to use a variable parameter list, you need to devise some sort of terminator for the list (eg, always add a dummy NULL argument): 如果要使用变量参数列表,则需要为列表设计某种终结符(例如,始终添加虚拟NULL参数):
find (word, NULL);
find (word, filename, NULL);
or supply the number of parameter as parameter: 或提供参数数量作为参数:
find (1, word);
find (2, word, filename);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.