【发布时间】:2018-10-16 02:55:10
【问题描述】:
我想我搞砸了一些我看不到的简单事情,但应该发生的是选择了添加新节点的菜单选项。主程序创建一个新节点,将其传递给将其添加到链表末尾的函数。下面是代码 sn-ps,应该有助于解释我做了什么。
节点声明:
typedef struct Node {
char fname[51];
char lname[51];
int idnum;
float scores[5];
float average;
struct Node *next;
} Node;
新节点创建和用户赋值:
case 'A':
entry = (Node*)malloc(sizeof(Node));
printf("Enter the name of the record you would like to append\nFirst:");
scanf("%50s", &(*entry).fname);
printf("\nLast:\n");
scanf(" %50s", &(*entry).lname);
printf("Enter the ID of the record you would like to append\n");
scanf("%d", &(*entry).idnum);
printf("Enter the scores of the record you would like to append\n");
for(j=0;j<5;j++) {
scanf("%f", &(*entry).scores[j]);
}
head = addend(head,entry);
printrecords(head,disp);
break;
将节点添加到链表的末尾:
Node* addend(Node* head, Node* entry) {
if(head == NULL) {
return NULL;
}
Node *cursor = head;
while(cursor->next != NULL) {
cursor = cursor->next;
}
cursor->next = entry;
return head;
}
非常感谢任何帮助。
已解决:
当我传递要分配给它的节点时,我不确定为什么要创建一个新节点。代码已更新以反映这一点。同样正如@jose_Fonte 指出的那样,在正式环境中使用此代码是有风险的,因为对 head 的引用可能会丢失。
【问题讨论】:
-
head = NULL这不是你想要的。 -
应该改为“==”吗?
-
确实,
=是一个作业。 -
if(head = NULL) {表示您没有完全启用编译器警告。 (我希望收到警告)节省时间,启用它们或获取新的编译器。 -
代码更新为在这种情况下还包括一个中断,因为它也丢失了。
标签: c memory-management linked-list allocation