gpt4 book ai didi

c - 段错误: 11 for my dynamic linked list

转载 作者:行者123 更新时间:2023-11-30 16:36:29 25 4
gpt4 key购买 nike

data.h

struct Sub {
int n;
struct Sub *next;
}

struct Super {
struct Sub *Sub
void (*addSub)(struct Super *self, struct Sub *subRef);
}

数据.c

static void addSub(struct Super *self, struct Sub *subRef) {
struct Sub *head = self->Sub;

while(head != NULL) { // throwing segmentation fault somewhere here
head = head->next;
}

// assign subRef once we reach to the end.
}

struct Super *newSuper() {
struct Super *super = malloc(sizeof(struct Super));
super->addSub = addSub;
return super;
}

data_test.c

int main() {
struct Super *super = newSuper();
super->addSub(super, malloc(sizeof(struct Sub)));
return 0;
}

我对 C 比较陌生,很久以前就实现了链表,但似乎无法解决空问题,过去就是这样。如何检测列表的末尾并将新值添加到末尾?

最佳答案

你必须初始化你的新对象

struct Super *newSuper() {
struct Super *super = malloc(sizeof(struct Super));
super->addSub = addSub;
super->Sub = NULL;
return super;
}

malloc 的内存未清除为任何值;它包含垃圾。

您还应该有一个 newSub 函数来创建 Sub 对象的实例,而不是使用原始 malloc 的调用者

关于c - 段错误: 11 for my dynamic linked list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48470101/

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