结构指针指针问题;双向链表相关

时间:2015-04-09 13:47:15

标签: c pointers

嗯,在某些情况下我得到了意外的指针移位,例如:有一个函数在给定元素之前将新节点插入到列表中。在插入时,它会使before_which指向另一个节点,这不应该发生。

事实上,在输入此消息时,我意识到使用DList * before_which没有任何意义并通过用DList before_which替换它来修复所有内容 - 但现在我很好奇:为什么使用指针指针导致这样的事情?

    typedef struct DListStruct {
        Pointer data;
        struct DListStruct *prev;
        struct DListStruct *next;
    } *DList;

    int dlist_insert_prev (DList *before_which, Pointer ins_value) {
        if (*before_which) {
            DList new_element=malloc(sizeof(struct DListStruct));
            if (!new_element) return 0;

            //[The part causing problems]
            if((*before_which)->prev) {
                new_element->data = ins_value;
                new_element->prev = (*before_which)->prev;
                new_element->next = *before_which;
                (*before_which)->prev->next = new_element;
                (*before_which)->prev = new_element;
                return 1;
            }
            //[/The part causing problems]
            else {  //This one is OK. Insertion into the beginning of the list
                new_element->data = (*before_which)->data;
                new_element->next = (*before_which)->next;
                new_element->prev = *before_which;
                (*before_which)->next->prev = new_element;
                (*before_which)->next = new_element;
                (*before_which)->data = ins_value;
                return 1;
            }
        }
        return 0;
    }

这里的图表: Diagram

有一个错误:图片上的指针应该是* before_which而不是before_which

UPD:为了比较,一个工作版本。什么都没有改变,但论证的类型。

    int dlist_insert_prev (DList before_which, Pointer ins_value) {
        if (before_which) {
            DList new_element=malloc(sizeof(struct DListStruct));
            if (!new_element) return 0;

            if(before_which->prev) {
                new_element->data = ins_value;
                new_element->prev = before_which->prev;
                new_element->next = before_which;
                before_which->prev->next = new_element;
                before_which->prev = new_element;
                return 1;
            }
            else {
                new_element->data = before_which->data;
                new_element->next = before_which->next;
                new_element->prev = before_which;
                before_which->next->prev = new_element;
                before_which->next = new_element;
                before_which->data = ins_value;
                return 1;
            }
        }
        return 0;
    }

0 个答案:

没有答案