c - 尝试更通用的 c 代码,自定义数据结构,在双链表中,这可能吗?

标签 c linked-list

我正在尝试重构一些代码,以减少重复。

这是一个精选示例,目前在每个 .c 文件中定义。

struct hrentry_t
{
    int custom1;
    int custom2;
    int custom3;

    struct hrentry_t *prev, *next;
};

struct hrentry_t*
attachentry(struct hrentry_t* hentry)
{
    struct hrentry_t* hnew = calloc(sizeof(struct hrentry_t), 1);
    if (hnew == NULL)
        return NULL;

    if (hentry != NULL) {
        while (hentry->next != NULL) {
            hentry = hentry->next;
        };
        hentry->next = hnew;
        hnew->prev = hentry;
    }
    return hnew;
}

https://github.com/techzilla/check_snmp_extras , 是整个代码库。

我正在声明并初始化一个自定义双链表,以及相应的分配函数。如果我将链接列表函数和代码移动到公共(public)库 .c 和 .h,我如何才能在每个列表条目中获取文件特定数据?每个文件都需要不同类型和数量的变量。

也许我做一个只包含上一个下一个和数据的双向链表?然后以某种方式使数据成为不完整结构的句柄?那需要如何分配呢?我愿意完全重新考虑我的方法,因此总是感谢经验丰富的编码人员提供的可靠建议。

最佳答案

一种方法是使您的专用列表数据类型可转换为通用双链表结构。这可以通过将非专用数据成员放在结构的开头来实现:

struct node_t {
    struct node_t * prev, * next;
};

struct hrentry_t
{
    struct node_t node;

    int custom1;
    int custom2;
    int custom3;
};

然后将 hentry_t* 转换为 node_t* 是有意义的。您的附件函数的签名变为:

struct node_t* attachentry(struct node_t* node);

要使用它,您需要将专用类型的实例转换为通用类型:

struct hentry_t * my_hentry_ptr;  /* initialized somehow... */
my_list = attachentry((struct node_t*)my_hentry_ptr);

关于c - 尝试更通用的 c 代码,自定义数据结构,在双链表中,这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784303/

相关文章:

c - 根据\n 将字符数组分成多个部分

c - 在 C 中更多地了解 pthreads

java - 重复链表值

C++:shared_ptr 泄漏,链表

javascript - 为什么这个 javascript add() 函数会为链表返回节点?

c - 如何将单词输入到链接列表中?

c - 当我在 C 语言的结构中声明一个数组时会发生什么?

c - 变长参数列表

c - 在我的 C 程序中使用 scanf 代替 fgets 和 fputs ?

c - c add_before 和 add_after 函数中的链表