我知道当您尝试访问程序范围之外的内存时会发生设置错误,但我无法弄清楚我的错误发生在哪里,也不知道为什么。我定义了一个列表: *ListType list = NULL; , 然后我将数据添加到列表中,调用 main 中的添加函数: addNodeToList(&列表, 歌曲);
void addNodeToList(ListType **list, SongType *song)
{
printf("Starting Add");
NodeType *newNode = malloc(sizeof(NodeType));
NodeType *currNode;
currNode = (*list)->head;
newNode->data = song;
newNode->next = NULL;
if(currNode == NULL) {
printf("List is Empty");
(*list)->tail = newNode;
(*list)->head = newNode;
}
else {
(*list)->tail->next = newNode;
(*list)->tail = newNode;
}
}
我传递的歌曲已正确初始化,我可以访问它的元素,所以我知道这不是导致段错误的原因。任何帮助将不胜感激!
typedef struct Song {
char title[MAX_STR];
char artist[MAX_STR];
char album[MAX_STR];
char duration[MAX_STR];
} SongType;
typedef struct Node {
struct Node *next;
SongType *data;
} NodeType;
typedef struct List {
NodeType *head;
NodeType *tail;
} ListType;
最佳答案
在 main
中声明
ListType* list = NULL;
然后在你调用的函数中
(*list)->head
取消引用 (*list)
很好,但是一旦您执行 ->head
,它就会尝试取消引用原始的 NULL
赋值。您需要先为 list
分配一些空间。
关于c - C--Linked List中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461379/