为什么修改数据字段会更改链接列表中的其他字段

时间:2014-04-05 23:54:28

标签: c struct

我想在createDDCL()方法中逐个插入节点并打印printDDClinkList()方法中的所有元素,但createDDCL()方法中有一些奇怪的错误:

enter image description here enter image description here enter image description here

//BiDirection link list
typedef struct DDCL{
    int data;
    struct DDCL *priv;
    struct DDCL *next;
}*BiDirectionLink;


BiDirectionLink createDDCL(){//带头结点的双向循环链表
    int n = 0,i=0;
    BiDirectionLink head = (BiDirectionLink)malloc(sizeof(BiDirectionLink));
    BiDirectionLink newNode,lastNodw;

    head->next = head;
    head->priv = head;
    lastNodw = head;
    printf("how many node do you want?\n:");
    scanf("%d",&n);
    for (; i<n; i++) {//append new node to the last
        newNode = (BiDirectionLink)malloc(sizeof(BiDirectionLink));
        newNode->priv = lastNodw;
        newNode->next = head;//new node's next always head
        head->priv = newNode;//th privious one of the head always the last
        lastNodw->next = newNode;
        newNode->data = i;
        lastNodw = newNode;       
    }
    return head;
}

详细!!!!!!!!!!!

void printDDClinkList(BiDirectionLink head){
    BiDirectionLink node = head->next;
    while (node->next != head) {
        printf("%d ",node->data);
        node = node->next;
    }
}

void testDDCLinkList(){
    printDDClinkList(createDDCL());
}
int main(int argc, const char * argv[])
{
    testDDCLinkList();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

问题在于:您只为指针分配了足够的内存,而不是整个结构

这就是你所做的:

newNode = (BiDirectionLink)malloc(sizeof(BiDirectionLink));

与此相同:

newNode = (struct DDCL *)malloc(sizeof(struct DDCL *));

但是,这就是你想要做的事情:

newNode = (struct DDCL *)malloc(sizeof(struct DDCL));

我的推荐?从来没有typedef指针。