通用链表中void指针类型转换的语法问题求助
通用链表中void*类型的正确访问方式
核心语法错误修正
你的printf语句里类型转换的优先级处理错了,->运算符优先级高于强制类型转换,必须先把f_llist.head->info用括号包裹后再转换为person*类型,才能正确访问成员。
正确的打印代码:
printf("%d", ((person*)f_llist.head->info)->test);
也可以用结构体的完整类型名:
printf("%d", ((struct _person*)f_llist.head->info)->test);
其他必改的潜在问题
- 链表未初始化:声明
llist f_llist;后,head和tail是未初始化的野指针,直接操作会导致未定义行为,必须初始化为NULL:llist f_llist = {NULL, NULL}; - main参数名颠倒:标准写法是
int main(int argc, char **argv),虽然不影响运行,但建议修正避免混淆。 - 空链表的tail更新:当链表为空时,pushhead后tail也应该指向新节点,否则tail会一直是NULL,后续操作可能出错。
完整修正代码
#include <stdlib.h> #include <stdio.h> typedef struct _person { int test; } person; typedef struct _node { void * info; struct _node * next; } node; typedef struct _llist { struct _node * head; struct _node * tail; } llist; void pushhead(llist * ff_list, void * info) { node * new_node = (node *)malloc(sizeof(node)); new_node->info = info; new_node->next = ff_list->head; ff_list->head = new_node; // 空链表时更新tail if (ff_list->tail == NULL) { ff_list->tail = new_node; } } int main(int argc, char **argv) { llist f_llist = {NULL, NULL}; person member; member.test = 5; pushhead(&f_llist, &member); // 正确访问test成员 printf("%d\n", ((person*)f_llist.head->info)->test); return 0; }
内容的提问来源于stack exchange,提问作者Ratdude
相关产品推荐
相关产品推荐

