gpt4 book ai didi

c - 如何编写通用函数来获取原子列表的长度

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

我定义的结构如下:

typedef struct decls  *Decls;
typedef struct expr *Expr;
struct decls {
Decl first;
Decls rest;
};
struct exprs {
Expr first;
Exprs rest;
};

然后我定义了一个函数来获取 Decl 的长度

static int list_length(Decls decls) {
if (decls) {
return 1 + list_length(decls->rest);
} else {
return 0;
}
}

如何在不定义另一个副本的情况下使此函数通用以获取 Exprs 的长度?

最佳答案

使用泛型列表并在第一部分存储指向对象(Expr 或 Delc)的指针,并首先转换为指向适当类型的指针以使用它。

struct list {
void *first;
struct list *rest;
};

static int list_length(struct list *l) {
if (l) {
return 1 + list_length(l->rest);
} else {
return 0;
}
}

关于c - 如何编写通用函数来获取原子列表的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23426401/

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