我正在尝试学习 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].stnumber
和 id
之间的匹配:
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/