【发布时间】:2019-12-25 23:53:47
【问题描述】:
所以我想用 C 语言编写一个函数,将泛型数组转换为单个链表。
我写的代码:
typedef struct Node {
struct Node* next;
void *value;
} Node;
void insert(Node** root, void* value) {
Node* new_node = (Node *) malloc(sizeof(Node));
Node* ptr;
new_node->value = value;
new_node->next = NULL;
if (*root == NULL)
*root = new_node;
else {
ptr = *root;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = new_node;
}
}
Node* arr2list(void* array, size_t length) {
Node *root = NULL;
for(int i = 0; i < length; i++) {
insert(&root,&array[i]);
}
return root;
}
我为它写了一个小测试:
int main() {
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
Node* root = arr2list(arr, n);
while (root != NULL)
{
printf("%d,",*(int*) root->value);
root = root->next;
}
return 0;
}
但我得到垃圾值:-13308,-2145276560,-2145276560,-2145276560,-2145276560,。
我似乎找不到导致这些结果的错误。
可能是什么问题?
【问题讨论】:
-
@IłyaBursov 它说:“需要算术或指针类型的 'void' 类型的错误操作数”。
-
问题的第一个版本似乎是正确的。你为什么改变它?
-
@user3386109 有人建议更改它(虽然它是正确的,但后来他删除了他的评论)。约翰尼,虽然这是一个列表而不是数组。
-
是的,他错了。问题出在
arr2list的声明中。void *array应该是int *array。
标签: c arrays pointers linked-list