我是一个初学者,正在学习如何在 C 中创建链表。每当我尝试打印出列表时,列表打印得很好,但最后总是会出现分段错误。
当我使用 GDB 回溯时,它指向我的行 -> entry = *((*node).data); 在 printContents 函数中。
但是我不太确定它有什么问题。
下面是链表代码:
void createEmptyLinkedList(LinkedList *inList) {
inList = (LinkedList*)malloc(sizeof(LinkedList));
(*inList).head = NULL;
(*inList).tail = NULL;
(*inList).size = 0; //Keeps track of size of list
return;
}
void insertAtStart(LinkedList *inList, JournalEntry *inValue) {
LinkedListNode *newNode;
int listSize = (*inList).size;
newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
(*newNode).data = inValue;
(*newNode).next = (*inList).head;
(*inList).head = newNode;
((*inList).size)++;
return;
}
void printContents(LinkedList *inList) {
LinkedListNode *node;
JournalEntry entry;
node = (*inList).head;
while (node != NULL) {
entry = *((*node).data);
printf("%04d-%02d-%02d: %s\n", entry.year, entry.month, entry.day, entry.text);
/*Move node to the next node*/
node = (*node).next;
}
printf("Done!");
return;
}
//Free nodes recursively
void freeLinkedList(LinkedList *inList) {
freeNode((*inList).head);
free(inList);
return;
}
void freeNode(LinkedListNode *node) {
if (node != NULL) {
freeNode((*node).next);
free(node);
}
这是用于启动链表的主要函数:
int main() {
LinkedList list;
JournalEntry *value;
char* textToEnter;
value = (JournalEntry*)malloc(sizeof(JournalEntry));
createEmptyLinkedList(&list);
textToEnter = "Hello";
(*value).day = 10;
(*value).month = 5;
(*value).year = 2010;
strcpy((*value).text, textToEnter);
insertAtStart(&list, value);
printContents(&list);
freeLinkedList(&list);
return 0;
}
为了以防万一有人需要它,这里是头文件中声明的结构:
typedef struct LinkedListNode {
JournalEntry *data;
struct LinkedListNode *next;
} LinkedListNode;
typedef struct {
LinkedListNode *head;
LinkedListNode *tail;
int size;
} LinkedList;
typedef struct {
int day;
int month;
int year;
char text[1000];
} JournalEntry;