使用带有void指针参数的函数

时间:2016-07-04 02:44:21

标签: c void-pointers

我是一个C初学者,试验链接列表,我发现了一个Github回购。 create函数是这样写的:

Node* ListCreate(void* data) {
    Node *head = malloc(sizeof(Node));
    if ( head != NULL) {
        head->next = NULL;
        head->data = data;
    }
    return head;
}

我可以通过将void*更改为int,然后在main中执行以下操作来使用它:

Node *root = ListCreate(5);

但后来我读了一些关于void指针的内容,看起来它们可以用作类似C ++模板的泛型类型,如果我能弄清楚它们是如何工作的话会很有用。我尝试了几件事情,最接近我要做的就是没有错误,只有一个警告:

incompatible integer to pointer conversion passing 'int' to parameter of type 'void *'

我在这里错过了一步吗?我首先觉得我应该在函数定义中添加一些内容,但我假设编写它的人知道他们正在做什么而我只是没有在main中正确使用它。那么我应该以不同的方式将参数传递给此函数吗?

2 个答案:

答案 0 :(得分:1)

正如其他人在评论中所提到的,更适合为不同类型创建不同的列表。

但是如果你想使用相同的函数定义,那么使用可以将指针传递给你的数据(intchar)并将它们转换为void *

/* main: start */
int main(void)
{
    Node *list_head;  /* Points to first element in list */
    Node *node_tmp;   /* Just a temporary pointer */

    int   *pint;
    char  *pchar;

    /* create an empty list */
    list_head = NULL;

    /* Note that there is no error checking done for
     * malloc, which is not good
     */

    /* Create a node which points to int */
    pint = malloc(sizeof(int));
    *pint = 10; 
    node_tmp = ListCreate((void *) pint);
    /* Add this node to list */
    list_head = add(node_tmp, list_head);

    /* Create a node which points to char */
    pchar = malloc(sizeof(char));
    *pchar = 'c';
    node_tmp = ListCreate((void *) pchar);
    /* Add this node to list */
    list_head = add(node_tmp, list_head);

    /* print total number of nodes in list */
    print_tot_nodes(list_head);
    return 0;
}

addprint_tot_nodes的代码是为了简洁起见。

请注意,如果print_tot_nodes指向不同的数据类型,则adddata等函数将没有太多问题。但是如果你需要实现像Node *smallest(Node *head)这样的函数,它返回指向具有最小元素的节点的指针,那么它可能会变得复杂。

因此,对不同类型使用不同的列表更容易。但是,如果您需要使用与原始帖子中相同的函数定义,则可以cast指向某些数据类型的实际指针void *

答案 1 :(得分:0)

我认为需要包装数字文字(或演员?) 像这样:

void *BOX_VAR;//Not require if use GCC extension
#define BOX(type, value) ((*(type *)(BOX_VAR=malloc(sizeof(type))) = value), BOX_VAR)
#define UNBOX(type, value) (*(type *)(value))

Node *list = ListCreate(BOX(int, 5));
int v = UNBOX(int, list->data);
printf("%d\n", v);
相关问题