gpt4 book ai didi

c - 可变参数列表 : possibility to collect them in variable?

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:56 25 4
gpt4 key购买 nike

当 C 函数定义可变参数列表时

myfunc(int *i,...);

我可以调用它(根据它的正确用法),例如与

myfunc(&i,1,"hello",2,42);

myfunc(&i,"fish",13,33,"haktar",2,42);

但是否也有可能将这些参数数据收集在一个列表中,然后将其交给函数?意味着是否有可用的变量类型允许这样的事情(伪代码):

arg_list list;

list.add("fish");
list.add(13);
list.add(33);
list.add("haktar");
myfunc(&i,list);

如果是:如何才能做到这一点?谢谢!

编辑:澄清一下:myfunc(int *i,...) 是给定的函数原型(prototype),无法修改,这意味着我必须使用合适的方法处理“...”参数部分(va_arg-like?)数据类型,我不能在那里使用简单的数组/链表/其他自己的数据类型。

最佳答案

您不能直接调用需要可变参数列表的函数。相反,您可以更改函数以接收例如包含允许参数类型 union 的项目数组:

#include <stdio.h> 

enum arg_type { ARG_TYPE_INTEGER, ARG_TYPE_STRING };

struct arg {
enum arg_type type;
union {
int integer;
const char *string;
};
};


static void myfunc(size_t length, struct arg list[length])
{
for (size_t i = 0; i < length; i++) {
printf("argument %zu: ", i);
switch (list[i].type) {
case ARG_TYPE_INTEGER: printf("integer: %d", list[i].integer); break;
case ARG_TYPE_STRING: printf("string: %s", list[i].string); break;
}
puts("");
}
}


int main()
{
struct arg list[] = {
{ .type = ARG_TYPE_STRING, .string = "fish" },
{ .type = ARG_TYPE_INTEGER, .integer = 13 },
{ .type = ARG_TYPE_INTEGER, .integer = 33 },
{ .type = ARG_TYPE_STRING, .string = "haktar" }
};

myfunc(sizeof list / sizeof *list, list);
}

(请注意,这使用了 C11 语言功能;您可能需要在编译器中启用 C11 支持,例如,为 clang 或 gcc 使用 -std=c11 选项)

关于c - 可变参数列表 : possibility to collect them in variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32580955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com