void changeIndex(FrameNode **head, int numOfFrames)
{
int frameIndex = 0, i = 0;
char name[STR_LEN];
FrameNode* curr = *head;
FrameNode* prev = NULL;
FrameNode* nodeToChange = NULL;
printf("Enter the name of the frame:\n");
fgets(name, STR_LEN, stdin);
name[strcspn(name, "\n")] = 0;
while (!(searchFrame(head, numOfFrames, name)))
{
printf("Name is not exist in the list\n Please enter another name:");
fgets(name, STR_LEN, stdin);
name[strcspn(name, "\n")] = 0;
}
printf("Enter the index of the frame:\n");
scanf("%d", &frameIndex);
while (frameIndex > numOfFrames || frameIndex < 0)
{
printf("Name is not exist in the list\n Please enter another name:");
scanf("%d", &frameIndex);
}
getchar();
while (curr != NULL && i < numOfFrames)
{
if (strcmp(name, curr->frame->name) == 0)
{
nodeToChange = createFrame(head, numOfFrames, curr->frame->path, curr->frame->duration, curr->frame->name);
numOfFrames++;
numOfFrames = deleteFrame(head, numOfFrames, curr->frame->name);
}
curr = curr->next;
i++;
}
curr = *head;
i = 0;
if (*head != NULL)
{
while (i != frameIndex && curr->next != NULL)
{
prev = curr;
curr = curr->next;
i++;
}
prev->next = nodeToChange;
nodeToChange->next = curr;
}
else
{
*head = nodeToChange;
}
}
在这里,我试图通过其名称更改节点的索引。我有一个内部带有结构的节点。
它引发了一个错误,提示
prev = NULL
甚至以为我在第4个时间初始化了它(正确的值在nodeToChange
中设置)。所以我的问题是为什么会这样,您如何建议我修复它?
最佳答案
对于i= 0
和frameindex=0
的值,则while循环的条件失败,因此prev
已经是null
,并且您将访问出现错误的prev->next
。
为i=0&&frameindex==0
添加一个条件
并将while循环的输入条件更新为i<frameindex
而不是i!=frameindex