c - 如何将(枚举类型类型,...)传递给另一个需要(枚举类型类型,...)的函数?
问题描述
我有两个函数,我正在尝试调用第一个需要“(枚举类型类型,...)”的函数,第二个也需要“(枚举类型类型,...)”传递“va_list args”从第一个函数到第二个函数,请参阅:
#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]: %s\n", count, va_arg(args, const char *));
break;
case Integer:
fprintf(stdout, "int arg[%d]: %d\n", count, va_arg(args, int));
break;
case Double:
fprintf(stdout, "double arg[%d]: %f\n", count, va_arg(args, double));
break;
default:
fprintf(stderr, "unknown type specifier\n");
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¸
那么,这样做的方法是什么?可能吗?
解决方案
您似乎误解了可变参数函数。
该fn2
函数应该调用va_start
,然后fn1
使用va_list
.
然后你的代码应该调用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);
}
}
推荐阅读
- npm - 如何让 npm lite 服务器提供我网页的全部内容?
- php - 如何使用代码 ingnitor 锚标记从库中从数据库中获取字体图标来创建动态菜单
- mysql - MySQL 如何使用 SELECT UNION ALL 和其他参数插入表中?
- python - 在 Django 的 MultipleChoiceField 中动态添加选项
- javascript - Palindrome:寻找最短的字符串
- javascript - React Native FlatList - 多次重新渲染/安装子项目
- php - 最好使用什么?FPDF VS TCPDF
- python - 通过 HTTP POST 传递二进制文件
- java - getLastSignInTimestamp() 和 getCreationTimestamp() 无法正常工作
- performance - Azure 存储帐户超过 IOPS 限制