我正在尝试学习通用链表,但当我将这一行添加到我的代码中时
*(char*)(new_node->data + i) = *(char*)(new_data + i);
将new_ data的内容复制到新分配的存储器(struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
(我收到两个错误:
1.表达式必须是指向完整对象类型的指针
2."void*":未知大小的
我也使用了intptr_t
而不是char*
,但它不起作用。
struct Node
{
void* data;
struct Node* next;
};
void push(struct Node** head_ref, void* new_data, size_t data_size)
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = malloc(data_size);
new_node->next = (*head_ref);
//error
int i;
for (i = 0; i < data_size; i++)
*(char*)(new_node->data + i) = *(char*)(new_data + i);
(*head_ref) = new_node;
}
int main()
{
struct Node* start = NULL;
// Create and print an int linked list
unsigned int_size = sizeof(int);
int arr[] = { 10, 20, 30, 40, 50 }, i;
for (i = 4; i >= 0; i--)
push(&start, &arr[i], int_size);
/* printf("Created integer linked list is");
printList(start, printInt);
// Create and print a float linked list
unsigned float_size = sizeof(float);
start = NULL;
float arr2[] = { 10.1, 20.2, 30.3, 40.4, 50.5 };
for (i = 4; i >= 0; i--)
push(&start, &arr2[i], float_size);
printf("Created float linked list is");
printList(start, printFloat);*/
return 0;
}
不能对void*
指针进行指针算术运算。您需要在增量之前施放:
for (i = 0; i < data_size; i++)
*((char*)new_node->data + i) = *((char*)new_data + i);
但我建议您用string.h
中的标准库函数memcpy
或memmove
替换整个循环。
memmove(new_node->data, new_data, data_size);