链表:试图更改节点的索引

时间:2018-06-23 04:03:16

标签: c linked-list

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中设置)。

所以我的问题是为什么会发生这种情况以及如何建议我修复它?

1 个答案:

答案 0 :(得分:0)

对于i= 0frameindex=0的值,则while循环的条件失败,因此prev已经是null,您将访问引发的prev->next错误。

i=0&&frameindex==0添加一个条件 并将while循环的输入条件更新为i<frameindex而不是i!=frameindex