gpt4 book ai didi

c - 如何将字符串的空格分隔子字符串作为c中函数的参数传递

转载 作者:行者123 更新时间:2023-11-30 16:26:18 25 4
gpt4 key购买 nike

我从函数接收一个字符串(例如:"3 10 ABC"),并希望将其传递给另一个函数,例如 function(3,10,ABC)

我试图将它捕获到数组中。

但是参数的数量可能是可变的,所以有没有办法使用va_list来做到这一点?

最佳答案

va_list 是底层可变参数实现的接口(interface),而不是构造可变长度数组的方法。虽然很有趣,但 va_* 的一部分正在做一些事情,比如将基于寄存器的调用约定溢出到传统数组中,这使得依赖它来实现你想要的东西太麻烦了。

构造一个您感兴趣的数组并不困难。你的问题表明你想要混合类型;这意味着每个成员都必须是“胖子”:

struct Element {
enum { Int, String, Other } Type;
union {
long val;
char *str;
void *anon;
};
};

然后您只想(重新)分配它们的数组,直到解析完成。假设您的解析是空格分隔的,您可以使用传统的:

for (s = strtok(str, “ \t”); s; s = strtok(NULL, “ \t”)) {
struct Element *e = Extend(&EList);

if (isdigit(*s)) {
e->type = Int;
e->val = strtol(s, NULL, 0);
} else if (isalpha(*s)) {
e->type = String;
e->str = strdup(s);
} else {
e->type = Other;
e->anon = strdup(s);
}
}
...

最后,您需要一种构建列表的方法:

struct ElementList {
struct Element *list;
int nalloc;
int nused;
};
struct Element *Extend(struct ElementList *el) {
if (el->nused == el->nalloc) {
int nsize = el->nalloc ? el->nalloc * 3 / 2 : 10 ;
struct Element *t = realloc(el->list, sizeof(*t) * nsize);
if (t == NULL) {
return NULL;
}
el->nalloc = nsize;
el->list = t;
}
return el->list + el->nused++;
}
#define ELIST_INITIALIZER { .list = NULL, .nalloc = 0, .nused = 0 }

ps/免责声明:我在这个编辑器中写了这个,它可能有小问题,但应该说明你想要做什么。

关于c - 如何将字符串的空格分隔子字符串作为c中函数的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53112103/

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