我正在尝试学习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;
}
答案 0 :(得分:1)
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
和{之间的字符串比较的记录{1}}匹配:
id
确保if (strcmp (st[i].stnumber, id) == 0)
found = i;
. . .
return found;
具有列表中记录的index
的数值。 index
的回复不是search()
或1
。