C初学者在这里。我正在尝试创建一个函数,该函数返回在头文件中定义的struct的新实例。我在List_create
函数中执行此操作。当我尝试编译我的代码时,出现以下错误消息。
错误:使用不兼容类型“ void”的表达式初始化“ ListNode”(又名“ struct ListNode”)
我List_create
在test.c
文件中调用该函数。感谢您的帮助,我在掌握C的基本概念时遇到了麻烦,但是我正在尝试学习。
#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);
#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;
}
#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;
}
的返回类型calloc
为void*
。因此,*calloc(...)
是类型void
。
ListNode node = *calloc(1, sizeof(ListNode));
等效于:
ListNode node = (void)(<<some vale>>);
这就是编译器所抱怨的。您不能分配void
给ListNode
。您需要的是:
ListNode *node = calloc(1, sizeof(ListNode));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句