为什么我在我的C队列中得到分段错误(核心转储)



所以我试图在C中实现队列数据结构,但我一直得到这个错误:分段故障(核心转储)。我想它来自我的enqueue方法。有人能帮我解决这个问题吗?

This is my queue.c file

#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: %sn", current->data.name, current->data.birthdate);
    current = current->next;
  }
  printf("nPeople: %dn", 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;
}

当向例程传递值(如指针)时,为了使例程设置该值,必须传递其地址。因此,这一行:

createQueue(list);
应:

createQueue(&list);

如果您希望createQueue 设置变量的值。您还需要:

void createQueue(LinkedList** list)
{
    *list = (LinkedList*) calloc(1, sizeof(LinkedList));
}

别担心——每个C程序员都会在某个时候犯这个错误。有关更多信息,请搜索"按值或引用传递"one_answers"c指针到指针"。

您正在传递列表指针的值。你需要传递引用。

void createQueue(LinkedList** list)
{
  *list = (LinkedList*)calloc(1, sizeof(LinkedList));
}

和from main

createQueue(&list);

相关内容

  • 没有找到相关文章

最新更新