【发布时间】:2021-04-20 01:42:56
【问题描述】:
任务是将现有列表按长度排序到另一个嵌套列表中。
["x", "yy", "zzz", "f", "gg"] ergeben
[["x", "f"], ["yy",
"gg"], ["zzz"]]
我正在考虑使用结构节点中的 void 指针来存储另一个列表,即主列表的每个节点中的列表。但我不断收到以下错误
dereferencing 'void *' pointer
我也尝试过类型转换。可能还有其他问题,但由于上述问题,我还没有到达那里。
typedef struct Node {
void *value;
struct Node *next; // self-reference
} Node;
// Group elements in list. Equivalent elements (for which equivalent is true) are put
// in the same group. The result is a list of groups. Each group is itself a list.
// Each group contains items that are equivalent.
Node *group_list(Node *list, EqualFun equivalent) {
Node *list_new = malloc(sizeof(Node));
//list_new = NULL;
list_new->next = NULL;
(Node *)list_new->value = malloc(sizeof(Node));
(char *)(list_new->value->value) = list->value;
list_new->value->next = NULL;
Node *temp1 = list->next;
Node *list_tester1 = list_new;
Node *list_tester2 = list_new;
while (list_new != NULL) {
while (temp1 != NULL) { //for the list inside list_new
list_tester2 = list_tester1;
if (equivalent(list_new->value->value, temp1->value)) {
list_new->value = append_list(list_new->value, temp1->value);
} else {
while (list_tester2 != NULL) { // for outer list
if (!equivalent(list_tester2->value->value, temp1->value)) {
list_new = append_list(list_new->value, temp1->value);
list_new = append_list(list_tester2->value, temp1->value);
list_new = append_list(list_tester1->value, temp1->value);
}
list_tester2 = list_tester2->next;
}
}
list_new = list_new->next;
}
}
return list_new;
}
【问题讨论】:
-
void*是一个指针,它指向一个不完整类型的对象。您不能取消引用void*指针。编译器无法确定结果类型。例如。list_new->value->next=NULL;取消引用value即void*(这在您的代码中多次完成)。在使用(char *)(list_new->value->value)=list->value;取消引用之前,您在该声明之上 - 这仅部分解决了需要类似于((char *)(list_new->value)->value=list->value;的问题使用void*很好,但要了解限制。
标签: c list recursion casting void-pointers