c - 此员工数据库中的删除功能不起作用

标签 c database

我正在尝试用 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/

相关文章:

c - 解析 CSV 并将数据存储在结构数组中?

c - 数组静态声明中第一个元素的地址

c - 求 sum(1)+sum(2)+....+(n) 的总和

c - 我如何告诉 gcc 不要内联函数?

Android Room - 在查询中使用外键

php - 在 View 中显示图像在 Laravel 中不起作用

c - C 的工作良好且全面的 ADT

c# - 每20秒保存一个字符串;将其保存到数据库或文本文件中更快吗?

mysql - 错误 1452 : 23000 Cannot add or update a child row. ..mysql

java - catch PacketTooBigException() block 在 Hibernate 中不起作用