链表尾插节点时头指针地址未更新问题排查求助
问题分析与修复方案
你遇到的链表始终为NULL的问题,核心是两个关键逻辑错误加上一个拼写小问题,下面逐一拆解并给出修复方案:
1. 传递局部变量地址导致main中的head/tail未被修改
在addNode函数里,你错误地创建了局部的head和tail变量,然后把它们的地址传给insertNode:
node*head = *headref; node*tail = *tailref; // ... insertNode(&head, &tail, studentNIM, studentName, attendance);
这里的head和tail是addNode的局部变量,insertNode中修改的只是这些局部变量的值,完全不会影响main函数里原始的head和tail指针!
修复方式:直接传递headref和tailref本身(它们已经是指向main中head/tail的二级指针):
// 删掉局部的head和tail变量,直接传参数里的二级指针 insertNode(headref, tailref, studentNIM, studentName, attendance);
2. main函数中tail指针未初始化
在main里你只声明了node*tail ;,但没有初始化为NULL,这是一个野指针,会导致后续操作出现未定义行为(比如打印奇怪的地址、程序崩溃等)。
修复方式:初始化tail为NULL:
int main(){ int choice; node*head = NULL; node*tail = NULL; // 这里加上初始化 printf("%p\n%p\n", head, tail); // ... 其余代码不变 }
3. 变量名拼写错误(次要但建议修正)
你的结构体里定义的是int attendace;(少了一个字母n),虽然当前赋值时拼写一致,但正确的单词是attendance,建议修正这个拼写避免后续维护混淆:
typedef struct data{ char studentNIM[13]; char studentName[33]; int attendance; // 修正拼写 struct data*next; }node;
同时insertNode中的赋值语句也要对应修改:
newNode->attendance = attendance;
修复后的关键代码片段
修改后的addNode函数
void addNode(node**headref, node**tailref){ char studentName[33]; int attendance; char studentNIM[13]; // 移除不必要的局部head/tail变量 printf("%p\n%p\n", *headref, *tailref); do{ printf("Enter student name(3 - 30 characters): "); fgets(studentName, 33, stdin); fflush(stdin); }while(strlen(studentName) < 4 || strlen(studentName) > 31); do{ printf("Enter student NIM(in number with length of 10 characters): "); fgets(studentNIM, 13, stdin); fflush(stdin); }while(digitCheck(studentNIM) == false || strlen(studentNIM) != 11); printf("Enter number of presence: "); scanf("%d", &attendance); fflush(stdin); // 直接传递二级指针 insertNode(headref, tailref, studentNIM, studentName, attendance); }
为什么之前的代码无法修改main中的head?
简单来说:当你在addNode里创建局部head变量时,它只是main中head的一个副本。传递&head给insertNode后,insertNode修改的是这个副本的值,函数返回后副本就被销毁了,main里的原始head自然不会有任何变化。而直接传递headref(它本身就是&main_head),insertNode里的*headref就直接对应main中的head指针,修改它才能真正改变链表的头指针。
内容的提问来源于stack exchange,提问作者Samuel Dave
相关产品推荐
相关产品推荐

