首页 > 解决方案 > 如何将(枚举类型类型,...)传递给另一个需要(枚举类型类型,...)的函数?

问题描述

我有两个函数,我正在尝试调用第一个需要“(枚举类型类型,...)”的函数,第二个也需要“(枚举类型类型,...)”传递“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¸

那么,这样做的方法是什么?可能吗?

标签: carguments

解决方案


您似乎误解了可变参数函数。

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);
    }
}

推荐阅读