gpt4 book ai didi

c - C. 段错误中的简单链表 11

转载 作者:行者123 更新时间:2023-11-30 20:17:13 25 4
gpt4 key购买 nike

我是 C 语言新手,这种语言让我有点困惑。当运行我非常简单的链表代码时,我不断收到段错误 11:

struct node{
int val;
struct node *next;
};

struct node *init(){
struct node *l = NULL;
return l;
}

struct node *newNode(int val){
struct node* n = init();
n = (struct node*) malloc(sizeof(struct node));
n->val = val;
n->next=NULL;
return n;
}

void append(struct node* h, int val){
struct node *temp;
temp = h;
int i = 0;
while(temp->next != NULL){
temp = temp->next;
i++;
}
printf("TestAppend");
temp= newNode(val);
}

int main(){
struct node* l = init();
printf("Test1\n");
append(l, 15);
printf("Test2\n");
struct node* temp = init();
temp = l;
}

有人可以解释一下为什么吗?谢谢:)

最佳答案

尝试将 init 函数更改为:

struct node *init()
{
void* p = malloc(sizeof(struct node));
return (struct node*)p;
}

编辑:并在最后释放它! ——伍德罗·巴洛

段错误是因为您的代码指向 NULL。

关于c - C. 段错误中的简单链表 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58438143/

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