gpt4 book ai didi

通用列表中的 C-Void 指针(包含结构)

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

我有 2 个不同的结构,但我需要将它们包含在同一个通用列表中。

结构是:

     typedef struct Val1{
int num1;
int num2;
int num3;
}Val1;



typedef struct Val2{
char name[50];
char surname[50];
int ID;
}Val2;

列表是:

typedef stuct list {
void *value;
struct node *next;
}list;

typedef struct L_head{
node *head;
int num_members;
}L_head;

我需要使用相同的列表实现,但列表需要同时处理结构类型。我无法弄清楚如何初始化列表并将一些元素放入列表中。任何建议都会有所帮助。

最佳答案

C 的规范解决方案将为两个结构添加一个具有不同值的公共(public)初始字段。

typedef struct Val1 {
int discriminator;
int num1;
int num2;
int num3;
} Val1;

typedef struct Val2 {
int discriminator;
char name[50];
char surname[50];
int ID;
} Val2;

如果需要,您可以定义一个新结构。
这具有保留以前的布局和对齐保证的优点:

struct packed {
int discriminator;
union {struct Val1;struct Val2};
};

无论如何,您可以将它直接集成到节点中:

typedef stuct node {
struct node *next;
int discriminator; /* You might want to reserve 0 for no content */
union {struct Val1;struct Val2};
} node;

该解决方案的技术术语是“可区分 union ”。

关于通用列表中的 C-Void 指针(包含结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23061016/

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