我有两个函数,我正在尝试调用第一个需要"(枚举类型类型,…(";到第二个也需要";(枚举类型类型,…(";通过";列表参数";从第一个功能到第二个功能,请参见:
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
enum types {
String, Integer, Double, Float = Double,
End
};
void fn1(enum types type, va_list args);
void fn2(enum types type, ...);
int main() {
fn1(Integer, 3);
return 0;
}
void fn1(enum types type, va_list args) {
va_list argsCopy;
va_copy(argsCopy, args);
fn2(type, &argsCopy);
va_end(argsCopy);
}
void fn2(enum types type, ...) {
va_list args;
int count;
va_start(args, type);
count = 0;
while (type != End) {
switch (type) {
case String:
fprintf(stdout, "char arg[%d]: %sn", count, va_arg(args, const char *));
break;
case Integer:
fprintf(stdout, "int arg[%d]: %dn", count, va_arg(args, int));
break;
case Double:
fprintf(stdout, "double arg[%d]: %fn", count, va_arg(args, double));
break;
default:
fprintf(stderr, "unknown type specifiern");
break;
}
type = va_arg(args, enum types);
count++;
}
va_end(args);
}
我得到了:
Segmentation fault
所以我尝试了这个宏:
#ifdef HAVE_VA_LIST_AS_ARRAY
#define MAKE_POINTER_FROM_VA_LIST_ARG(arg) ((va_list *)(arg))
#else
#define MAKE_POINTER_FROM_VA_LIST_ARG(arg) (&(arg))
#endif
//...
void fn1(enum types type, va_list args) {
fn2(type, MAKE_POINTER_FROM_VA_LIST_ARG(args));
}
//...
我得到了:
int arg[0]: 571263040
unknown type specifier
unknown type specifier
char arg[3]: UHåAWAVAUATSHì(L%X¸
那么,怎么做呢?有可能吗?
您似乎误解了vararg函数。
fn2
函数应该调用va_start
,然后用va_list
调用fn1
。
然后您的代码应该调用fn2
。您必须记住在参数列表的末尾添加End
枚举。
所以你的代码应该是:
fn2(Integer, 123, End);
然后fn2
应该类似于:
void fn2(enum types type, ...)
{
va_list args;
va_start(args, type);
fn1(type, args);
va_end(args);
}
最后把你的循环和打印放在fn1
函数中:
void fn1(enum types type, va_list args)
{
while (type != End)
{
// ...
type = va_arg(args, enum types);
}
}