c - 定义一个delete(student st[], int *itemcount)函数来从学生对象数组中删除目标记录

标签 c arrays struct typedef

我正在尝试学习 C 编程,所以我尝试做一些练习。如下所示,搜索函数仅返回 1 或 -1,并且变量索引用于确定目标学生是否存在。但之后它再次被用来确定它是数组中的最后一项、中间项还是第一项。当我们已经将搜索函数的返回值分配给索引时,索引如何具有该数值?请帮我解决这个问题。谢谢。

//function to delete record
void
delete_rec (student st[], int *itemcount) {
    char id[10];
    int index, i;
    if (*itemcount > 0) {
        printf ("Enter student's ID:");
        scanf ("%s", id);
        index = search (st, id, *itemcount);

        if ((index != -1) && (*itemcount != 0)) {
            if (index == (*itemcount - 1))  //delete the last record
            {

                clean (st, index);
                --(*itemcount);

                printf ("The record was deleted.\n");
            } else      //delete the first or middle record
            {
                for (i = index; i < *itemcount - 1; i++) {
                    st[i] = st[i + 1];
                    clean (st, *itemcount);
                    --(*itemcount);
                }

            }

        } else
            printf ("The record doesn't exist.Check the ID and try again.\n");


    } else
        printf ("No record to delete\n");
}

//function to clean deleted record
void
clean (student st[], int index) {

    strcpy (st[index].stnumber, "");
    strcpy (st[index].stname, "");
    st[index].sex = NULL;
    st[index].quizz1 = 0;
    st[index].quizz2 = 0;
    st[index].assigment = 0;
    st[index].midterm = 0;
    st[index].final = 0;
    st[index].total = 0;

}

最佳答案

how can index have that numeric value when we already assigned 
the returned value from the search function to it?

index(从 search() 返回的值)在搜索中设置为字符串比较的记录的实际循环索引 st[i].stnumberid 之间的匹配:

if (strcmp (st[i].stnumber, id) == 0)
    found = i;
. . .
return found;

这可确保 index 具有列表中记录的 index 的数值。 search() 的返回值不是 1-1

关于c - 定义一个delete(student st[], int *itemcount)函数来从学生对象数组中删除目标记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24460140/

相关文章:

php - 使用 AJAX 将 Javascript 字符串发送到 PHP 文件,然后从文件返回数组

c# - 在 C# 中将字节读入结构

pointers - 反射匿名结构体字段指针

使用回溯的随机遍历 N * M 网格的复杂性

c++ - 打印伪多维数组时出现问题

javascript - 使用 Vanilla JavaScript 搜索对象数组

python - struct.unpack(...) 在 x64 机器上的工作方式不同

c - 链接到 C 中的特定库时运行时精度损失

c - System C 命令和内存限制?

c - 快速制作静态链表