出现段错误的原因有哪些? 在下面的代码中,我尝试创建一种使用链接列表的简单方法。 基本上在我的程序中,您只需使用 linkedList 结构类型创建一个列表。 然而,程序中有一行导致了段错误。为什么会出现这种情况? 任何帮助将非常感激。谢谢:)
#include <stdio.h>
#include <stdlib.h>
struct node{
int num;
struct node *next;
};
//Make the struct
typedef struct {
struct node * first;
struct node * current;
}linkedList;
void addNode(linkedList list, int a);
void addFirstNode(linkedList list, int b);
//Function prototypes
int main() {
linkedList list;
addFirstNode(list, 1);
addNode(list, 2);
addNode(list, 3);
addNode(list, 4);
addNode(list, 5);
addNode(list, 6);
addNode(list, 7);
}
void addFirstNode(linkedList list, int input) {
list.first = (struct node *)malloc(sizeof(struct node)); //Make first node
list.first -> num = input; //Fill first node
list.current = list.first;
}
void addNode(linkedList list, int input) {
struct node * newNode = (struct node *)malloc(sizeof(struct node));
newNode -> num = input;
list.current -> next = newNode; //Segmentation fault! (core dumped)
list.current = newNode;
}
最佳答案
正如评论中所指出的,您的代码中有很多地方需要纠正:
- 您需要通过引用传递函数参数(C 通过值传递元素)。
- 您需要初始化链接列表,否则您将尝试取消引用 NULL 指针。
这是代码的正确版本:
#include <stdio.h>
#include <stdlib.h>
struct node{
int num;
struct node *next;
};
//Make the struct
typedef struct {
struct node * first;
struct node * current;
}linkedList;
void addNode(linkedList* list, int a);
void addFirstNode(linkedList* list, int b);
//Function prototypes
int main() {
linkedList *list = (struct node *)malloc(sizeof(struct node));;
addFirstNode(list, 1);
addNode(list, 2);
addNode(list, 3);
addNode(list, 4);
addNode(list, 5);
addNode(list, 6);
addNode(list, 7);
}
void addFirstNode(linkedList* list, int input) {
list->first = (struct node *)malloc(sizeof(struct node)); //Make first node
list->first->num = input; //Fill first node
list->current = list->first;
}
void addNode(linkedList *list, int input) {
struct node * newNode = (struct node *)malloc(sizeof(struct node));
newNode->num = input;
list->current->next = newNode; //Segmentation fault! (core dumped)
list->current = newNode;
}
关于c - 为什么会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293064/