我对 C 相当陌生,我知道我可能在指针方面做错了什么,但我似乎无法准确指出我做错了什么。
这是链表的结构和函数:
// node structure
struct Node {
int val;
struct Node* next;
};
// singly linked list structure
struct LinkedList {
int size;
struct Node* head;
} LinkedList = {0, NULL};
// insert at head function
void InsertHead(struct LinkedList* list, int val) {
struct Node* node = malloc(sizeof(struct Node));
node->val = val;
node->next = list->head;
list->head = node;
list->size++;
}
// print values in list
void PrintList(struct LinkedList* list) {
struct Node* node = list->head;
while (node != NULL) {
printf("%d, ", node->val);
node = node->next;
}
printf("\n");
}
当我尝试使用以下代码调用PrintList时:
// main function
int main() {
struct LinkedList* mylist = malloc(sizeof(LinkedList));
InsertHead(mylist, 4);
InsertHead(mylist, 3);
InsertHead(mylist, 1);
// printf("%d, ", mylist->head->val);
// printf("%d, ", mylist->head->next->val);
// printf("%d, ", mylist->head->next->next->val);
// printf("\n");
PrintList(mylist);
return 0;
}
我收到错误段错误:11
当我运行删除对 PrintList 函数的调用并取消注释 printf 语句时,我得到了所需的输出:
1,3,4,
我在这里缺少什么?
最佳答案
您永远不会初始化在 main()
顶部分配的 struct LinkedList
。
因此,当您遍历列表以打印它时,在显式插入的三个元素之后,最后一个元素的 next
字段将包含 head
中的任何垃圾。分配时原始 LinkedList
的 code> 字段。
要解决此问题,您可以使用 calloc
来分配它(这会在分配给您之前将分配的内存显式清零),或者编写一个同时分配 和 显式初始化一个 struct LinkedList
。
关于c - 段错误: 11 when trying to print linked list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57342641/