我的代码提示用户输入用户想要从指针数组中删除的名称,然后在链接列表中搜索并删除该名称。但我的代码正在删除指针数组中的所有名称,除了数组中的最后一个名称。这是我的删除功能。
int delete (studPtr *sPtr, Student myStud)
{
studPtr previous = NULL;
studPtr current = NULL;
studPtr temp = NULL;
while ((*sPtr)->nextPtr != NULL)
{
//previous = *sPtr;
if ((*sPtr)->name == myStud.name)
{
temp = *sPtr;
(*sPtr) = (*sPtr)->nextPtr;
current = (*sPtr);
previous->nextPtr = current;
free(temp);
}
else
{
previous = *sPtr;
(*sPtr) = (*sPtr)->nextPtr;
}
}
return 1;
}
这是我的指针数组
char *studentname[] = { "Abbie", "Oakley", "Sylvia", "Uwe", "Ken", "Aaron", "Fabien",'\0' };
这会调用该函数。
printf("Enter students name: \n");
scanf("%s", Stud.name);
int convert_char = determineIfConvert(Stud.name);
if (convert_char == 1)
{
convert(Stud.name);
}
int delete_student = delete(&startPtr, Stud);
if (delete_student == 1)
{
printf("student deleted");
printList(startPtr);
}
else
{
printf("student not found\n");
}
最佳答案
数组中的最后一个元素不会被删除,因为 (*sPtr)->nextPtr
在该实例中为 NULL,并且 while 循环被终止并且 if ((*sPtr)->name == myStud.name)
不会被执行。
要解决这个问题,您可以使用 do while 循环。在 do while 循环之前,您需要检查 (*sPtr) 是否为 NULL
。
关于c - 我需要这部分代码的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36702403/