0

我正在尝试创建一个可遍历的链表,但是当我尝试向列表中添加一个元素时我的程序崩溃了。我已经尝试了很多事情,但我无法弄清楚我做错了什么。

typedef struct node_t node_t;
typedef struct list_t list_t;

struct node_t {
    void *data;
    node_t *prev;
    node_t *next;  
};

struct list_t {
    node_t front;
    node_t back;
};

list_t* listEmpty () {
    list_t *list = malloc (sizeof (list_t));
    list->front.prev = NULL;
    list->front.next = &(list->back);
    list->back.prev = &(list->front);
    list->back.next = NULL;
    return list;
}

void listPushFront (list_t *list, void *data) {
    node_t *newNode = malloc (sizeof (node_t));
    newNode->data = data;
    newNode->prev = &(list->front);
    newNode->next = list->front.next;
    list->front.next->prev = newNode;  //CRASHES HERE
    list->front.next = newNode;
}

int main (int argc, char *argv[]) { 
    list_t *list = malloc (sizeof (list_t));
    int a = 6; 
    void* pa = &a;
    listEmpty(list);
    listPushFront (list, pa);
    return 0;
}
4

3 回答 3

2

listEmpty()返回一个列表,并有一个 void 参数。但是main(),您将一个列表传递给它,而不是捕获它的返回值。

#include <stdlib.h>

typedef struct node_t node_t;
typedef struct list_t list_t;

struct node_t {
    void *data;
    node_t *prev;
    node_t *next;  
};

struct list_t {
    node_t front;
    node_t back;
};

list_t* listEmpty (void) {
    list_t *list = (list_t *)malloc (sizeof (list_t));
    list->front.prev = NULL;
    list->front.next = &(list->back);
    list->back.prev = &(list->front);
    list->back.next = NULL;
    return list;
}

void listPushFront (list_t *list, void *data) {
    node_t *newNode = (node_t *)malloc (sizeof (node_t));
    newNode->data = data;
    newNode->prev = &(list->front);
    newNode->next = list->front.next;
    list->front.next->prev = newNode;
    list->front.next = newNode;
}

int main (int argc, char *argv[]) { 
    list_t *list = 0;
    int a = 6; 
    void* pa = &a;
    list = listEmpty();
    listPushFront (list, pa);

    return 0;
}
于 2013-04-14T03:10:50.890 回答
0

您的列表未正确初始化,这会导致崩溃。

listEmpty(list);

应该

list = listEmpty();
于 2013-04-14T03:13:50.427 回答
0

这在很多方面都是错误的。

int main (int argc, char *argv[]) { 
    list_t *list = malloc (sizeof (list_t));

你为什么这样做main

为什么listEmpty用参数调用list

listEmpty(list);

您的listEmpty函数不会对您传递给它的参数做任何事情。

您没有对listEmpty返回的指针做任何事情,那么您如何期望它传播到以下调用listPushFront

于 2013-04-14T03:20:41.380 回答