我正在尝试创建一个可遍历的链表,但是当我尝试将一个元素添加到列表中时,我的程序崩溃了。我尝试了很多东西,但我无法弄清楚我做错了什么。
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;
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
您的列表未正确初始化,这导致崩溃。
listEmpty(list);
应该是
list = listEmpty();
答案 2 :(得分:0)
这在很多方面都是错误的。
int main (int argc, char *argv[]) {
list_t *list = malloc (sizeof (list_t));
你为什么要在main
中这样做?
为什么用参数listEmpty
来呼叫list
?
listEmpty(list);
您的listEmpty
函数对您传递给它的参数没有任何作用。
您对listEmpty
返回的指针没有做任何事情,那么您希望它如何传播到listPushFront
的后续调用?