所以我试图在C中实现Queue数据结构,但我不断收到此错误:分段错误(核心转储)。我认为它来自我的入队方法。有人可以帮我解决这个问题......
这是我的queue.c文件
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
void createQueue(LinkedList* list)
{
list = (LinkedList*)calloc(1, sizeof(LinkedList));
}
int isEmpty(LinkedList* list)
{
int empty = 0;
if(list->head == NULL)
{
empty = 1;
}
return empty;
}
void enqueue(LinkedList* list, Person p)
{
LinkedListNode* newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
newNode->data = p;
if (isEmpty(list))
{
list->head = list->tail = newNode;
} else
{
LinkedListNode* first = list->head;
first->previous = newNode;
newNode->next = list->head;
list->head = newNode;
}
list->count ++;
}
Person dequeue(LinkedList* list)
{
LinkedListNode* temp;
temp = list->tail;
list->tail = list->tail->previous;
list->count --;
return temp->data;
}
void viewQueue(LinkedList* list)
{
LinkedListNode* current;
current = list->head;
while (current != NULL)
{
printf("Name: %s Birthdate: %s\n", current->data.name, current->data.birthdate);
current = current->next;
}
printf("\nPeople: %d\n", list->count);
}
这是我的头文件......
#ifndef LINKED_LIST
#define LINKED_LIST
#define FALSE 0
#define TRUE !FALSE
typedef struct{
char name[20];
char birthdate[10];
} Person;
typedef struct LinkedListNode{
Person data;
struct LinkedListNode* next;
struct LinkedListNode* previous;
} LinkedListNode;
typedef struct{
LinkedListNode* head;
LinkedListNode* tail;
int count;
} LinkedList;
void createQueue(LinkedList* list);
int isEmpty(LinkedList* list);
void enqueue(LinkedList* list, Person p);
Person dequeue(LinkedList* list);
void viewQueue(LinkedList* list);
#endif
我也有这种方法来测试我的队列。当我运行它时,我得到一个分段错误。我的程序怎么了?
#include <stdio.h>
#include "queue.h"
int main(void)
{
LinkedList* list;
createQueue(list);
Person p1 = {"J Cole", "28/01/1985"};
Person p2 = {"Kendrick Lamar", "19/01/1994"};
Person p3 = {"Slim Shady", "17/10/1972"};
Person p4 = {"Tupac Shakur", "12/09/1971"};
enqueue(list, p1);
enqueue(list, p2);
enqueue(list, p3);
enqueue(list, p4);
viewQueue(list);
return 0;
}
答案 0 :(得分:2)
您正在传递列表指针的值。您需要传递参考。
void createQueue(LinkedList** list)
{
*list = (LinkedList*)calloc(1, sizeof(LinkedList));
}
从主
开始createQueue(&list);
答案 1 :(得分:2)
将值(如指针)传递给例程时,为了使例程设置该值,您必须传递其地址。因此,这一行:
createQueue(list);
应该是:
createQueue(&list);
如果您想将createQueue设置为设置变量的值。你还需要:
void createQueue(LinkedList** list)
{
*list = (LinkedList*) calloc(1, sizeof(LinkedList));
}
不要担心 - 每个C程序员都会在某些时候犯这个错误。有关更多信息,请搜索“按值传递或引用”和“指向指针的c指针”。