0

简而言之,我试图使用 void 指针作为函数指针的参数,但得到编译器错误“无效使用 void 表达式”。

我有一个双向链表(DLL),其节点结构如下:

typedef struct DL_LIST
{
    uint16 tag;                 /* Object ID tag */
    struct DL_LIST *previous;
    struct DL_LIST *next;
    void *object;               /* A pointer to this node's object */
    uint32 size;                /* The size of this node's object, in bytes */
} DL_LIST;

我还有以下用于删除单个此类节点的功能:

void dl_delete(DL_LIST *node, void (*dl_destructor)(void*)) {
    if (node != NULL) {
        dl_extract(node);       /* Removes the node from the list */

        if (node->object != NULL) {
            (*dl_destructor)(node->object);

            free(node->object);
        }

        free(node);
    }
}

其中节点提取函数为:

DL_LIST *dl_extract(DL_LIST *node) {
    if (node != NULL) {
        if (node->previous != NULL) {
            node->previous->next = node->next;
        }

        if (node->next != NULL) {
            node->next->previous = node->previous;
        }

        node->previous = NULL;
        node->next = NULL;
    }

    return node;
}

这里的想法是能够为object可能存储在节点中的每种类型传递一个单独的析构函数。此析构函数将指向对象的指针作为参数,用于释放object.

当我尝试dl_delete()从旨在删除整个 DLL 的函数中调用时,会发生上述错误:

void dl_destroy(DL_LIST **list, void (*dl_destructor)(void*)) {
    DL_LIST *marker;
    DL_LIST *previous_node;

    if (*list != NULL) {
        previous_node = (*list)->previous;

        while (previous_node != NULL) {
            marker = previous_node->previous;
            dl_delete(previous_node, (*dl_destructor)(previous_node->object));
            previous_node = marker;
        }

        /* Code removed for brevity */
    }
}

我已阅读函数指针介绍,但仍无法确定如何解决该问题。对我做错了什么的解释将不胜感激。

4

1 回答 1

3

这条线

dl_delete(previous_node, (*dl_destructor)(previous_node->object));

需要是dl_delete(previous_node, dl_destructor);

也在 dl_delete 这一行(*dl_destructor)(node->object);

应该dl_destructor(node->object);

另外,为了安全起见,我喜欢在尝试使用它们进行调用之前检查我的函数指针是否不为空

所以在 dl_delete 中是这样的:-

if(dl_destructor!=NULL) dl_destructor(node->object);
于 2013-02-13T03:10:35.967 回答