gpt4 book ai didi

c - 在C中将节点添加到链表时出现EXC_BAD ACCESS

转载 作者:行者123 更新时间:2023-11-30 18:53:01 25 4
gpt4 key购买 nike

我正在尝试实现一个在链表末尾添加新节点的函数,发现 here 。但是,当在 Xcode 中运行下面的代码时,我在标有注释//ERROR

的 if 语句中收到 EXC_BAD_ACCESS 错误

这是我第一次认真接触链表,有人能解释我做错了什么吗?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct _node {
int value;
struct _node *next;
} node;

int addNodeBottom(int val, node *head);

int main(int argc, const char * argv[]) {
node *head;
head = NULL;

for (int i = 1; i<11; i++) {
addNodeBottom(i, head);
}


node *temp = head;
while (head != NULL) {
head = temp->next;
free(temp);
temp = head;
}

return 0;
}

int addNodeBottom(int val, node *head){

//create new node
node *newNode = (node*)malloc(sizeof(node));

if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}

newNode->value = val;
newNode->next = NULL;

//check for first insertion
if(head->next == NULL){ //ERROR
head->next = newNode;
printf("added at beginning\n");
}

else {
//else loop through the list and find the last
//node, insert next to it
node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
}
return 0;
}

最佳答案

head = NULL;
...
if(head->next == NULL)

正因为如此。您应该首先将 head 初始化为有效指针。问题的可能解决方案是将 node** head 传递给函数而不是 node* headPtr 并检查 *headPtr == NULL 以使其有效可以使用head = NULL

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

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