尝试在C中初始化结构时出错

时间:2016-04-07 02:59:03

标签: c struct

C初学者。我试图创建一个函数来返回我在头文件中定义的struct的新实例。我在List_create函数中执行此操作。当我尝试编译我的代码时,我收到以下错误消息。

  

错误:初始化' ListNode' (又名' struct ListNode')表达式为不兼容的类型' void'

我在List_create文件中调用test.c函数。感谢任何帮助,我无法掌握C的基本概念,但我正在努力学习。

dll.h

#include <stdlib.h>

struct ListNode;

typedef struct ListNode {
    struct ListNode *next;
    struct ListNode *prev;
    void *value;
} ListNode;

typedef struct List {
    int count;
    ListNode *first;
    ListNode *last;
} List;

List *List_create();

void add_to_back(List *list, void *value);
void *remove_from_back(List *list);

void add_to_front(List *list, void *value);
void *remove_from_front(List *list);

void *remove_from_list(List *list, ListNode *node);

dll.c

#include <dll.h>

List *List_create()
{
    return calloc(1, sizeof(List));
}

void add_to_back(List *list, void *value)
{  
    ListNode node = *calloc(1, sizeof(ListNode));
    node->value = value;

    if (list->first == NULL) {
        list->first = node;
        list->last = node;
    } else {
        list->last->next = node;
        node->prev = list->last;
        list->last = node;
    }
}

void *remove_from_back(List *list)
{
    return 0;  
}

void add_to_front(List *list, void *value)
{
}

void *remove_from_front(List *list)
{
    return 0;
}

 *remove_from_list(List *list, ListNode *node)
{
    return 0;
}

test.c的

 #include <dll.h>
#include <stdlib.h>
#include <stdio.h>

int test_add_to_back() {
    List *list = List_create();

    int new_value = 1;
    add_to_back(list, &new_value);
    ListNode *curr = list->first;
    if (curr->value != &new_value) return 0;
    if (list->first->value != list->last->value || list->last->value != new_value) return 0;

    add_to_back(list, 2);   
    add_to_back(list, 3);   
    add_to_back(list, 4);   
    curr = list->first;

    if (list->last->value != 4) return 0;
    //if (curr-> (void) *value != 1) return 0;
    //curr = curr->next;
    //if (curr->(void) *value != 2) return 0;
    //curr = curr->next;
    //if (curr-> (void) *value != 3) return 0;
    //curr = curr->next;
    //if (curr->(void) *value != 4) return 0;

    return 1;
}

int main() {
    printf("helloworld\n");
    if(test_add_to_back() != 1) printf("Add to back test failed\n");
    return 0;
}

3 个答案:

答案 0 :(得分:2)

calloc的返回类型为void*。因此,*calloc(...)的类型为void

ListNode node = *calloc(1, sizeof(ListNode));

相当于:

ListNode node = (void)(<<some vale>>);

编译器抱怨的是什么。您无法将void分配给ListNode。你需要的是:

ListNode *node = calloc(1, sizeof(ListNode));

答案 1 :(得分:0)

变化:

ListNode node = * calloc(1, sizeof(ListNode));

ListNode *node = (ListNode*) calloc(1, sizeof(ListNode));

记住做

void *value;
如果希望做一些有用的事情,

会要求你做适当的类型转换 用它。事实上,void*用于多功能性。

答案 2 :(得分:0)

calloc可以返回(void *)指针,你应该改为:

  

列表* List_create()   {      return(List *)calloc(1,sizeof(List));   }   有些编译器要求你做合适的类型。

相关问题