gpt4 book ai didi

C结构多种类型

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:32 27 4
gpt4 key购买 nike

我想用 C 编写一个库,但我不知道推荐的方法是什么。例如,我得到了这样的结构和多个函数:

typedef struct example
{
int *val;
struct example *next;
} Example;

而且我有针对多种类型的 val

的构建函数
Example* build() { do sth };
Example* buildf() { do sth }; // val is float
Example* buildd() { do sth }; // val is double

什么是更好的做法(用于“专业”图书馆)。使用指向 void 和类型转换的指针或具有所有可能性的结构 - int、float、double。

最佳答案

使用union 和一些方法来存储类型信息:

typedef struct example
{
enum{ T_STRUCT_WITH_INT, T_STRUCT_WITH_FLOAT, T_SO_ON } type;
union {
int val_int;
float val_float;
} val;
struct example *next;
} Example;

通过s->val.val_int检查type后访问字段

在 C11 中,您可以使用匿名 union ,并且可以像 s->val_int 一样访问字段

关于C结构多种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34833068/

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