gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:52:32 25 4
gpt4 key购买 nike

当我尝试向我的链表中添加一个新节点时,编译器停止工作并且无法添加该节点,我无法找出问题是在逻辑中还是在语法中

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 ;
}
}

最佳答案

在您的 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));

关于c - 将新节点添加到c中的现有链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40683002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com