将新节点添加到c中的现有链接列表中

时间:2016-11-18 17:40:08

标签: c linked-list

当我试图将新节点添加到我的链接列表时,编译器停止工作并且无法添加节点,我无法在逻辑或语法中找出问题< / p>

struct Record* CreateNode() {
    struct Record* PointerToRecord ;
    PointerToRecord = (struct Record*) malloc(sizeof(struct Record*));
    if (PointerToRecord) {
        PointerToRecord->C = FillDataOfContacts();
        PointerToRecord->Next = NULL;
        PointerToRecord->Prev = NULL;
    }
    return PointerToRecord  ;
}

struct Record* AddNode() {
    if (Head == NULL && Tile == NULL) {
        Head = Tile = CreateNode();
    } else {
        struct Record* Pointer ;
        Pointer = CreateNode();
        Tile->Next = Pointer ;
        Pointer->Prev = Tile ;
        Pointer->Next = NULL;
        Tile = Pointer ;
    }
}

1 个答案:

答案 0 :(得分:3)

struct Record* CreateNode()函数中,您有:

PointerToRecord = (struct Record*) malloc(sizeof(struct Record*));

此处您没有分配足够的内存来存储struct record,而是指定内存来存储struct record*

尝试以这种方式分配:

PointerToRecord = (struct Record*) malloc(sizeof(struct Record));

此外,您无需转换malloc的返回值: Here's why (点击)

所以你可以用以下方式分配你的指针

PointerToRecord = malloc(sizeof(struct Record));