我正在尝试用 C 语言为员工数据库修复这段代码。可以按 ID 搜索员工,如果没有找到记录,则显示“抱歉,没有找到记录!”显示消息。
void del() {
char id[10];
printf("\n\t Delete which record?:");
gets(id);
curr = start;
if (strcmp(start->name, name) == 0) {
start = start->next;
free(curr);
printf("\n\t First record deleted!");
return;
}
while (curr) {
if (strcmp(curr->next->name, name) == 0) {
curr->next = curr->next->next;
printf("\n\n\t Record Deleted!");
return;
}
curr = curr->next;
}
printf("\n\n\t Sorry record not found!");
}
最佳答案
而不是测试while (curr)
, 你应该测试 while (curr->next)
,否则当 del
时,您将取消引用 NULL 指针没有找到匹配的记录。如果数据库为空,此函数也会失败,因为您取消了对 start
的引用。没有首先测试它不是 NULL
.
请注意,您不应使用 gets()
.此函数已从最新的 C 标准中删除,无法安全使用:如果用户输入超过 9 个字符的员工姓名,您的程序将调用未定义的行为。
使用指向指针的指针,可以避免对初始列表元素进行特殊封装:
void del() {
char id[128];
Employee **pp = &start;
printf("\n\t Delete which record?: ");
if (!fgets(id, sizeof id, stdin))
return;
id[strcspn(id, "\n")] = '\0'; /* strip the \n if present */
while (*pp) {
if (strcmp((*pp)->name, id) == 0) {
Employee *p = *pp;
*pp = p->next;
free(p);
printf("\n\n\t Record Deleted!");
return;
}
pp = &(*pp)->next;
}
printf("\n\n\t Sorry record not found!");
}
关于c - 此员工数据库中的删除功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834686/