如何引用嵌套结构中的指针?

时间:2017-05-17 15:33:04

标签: c pointers linked-list typedef

我对C指针比较陌生,所以我试着和他们一起玩弄他们如何工作,更深入。 我有以下数据类型,用typedef定义:

struct node
{
    int key;
    struct node * prev;
    struct node * next;
};

typedef struct node node_t;

struct list
{
    node_t * head;
    node_t * tail;
};

typedef struct list list_t;

我的目标是拥有一个双向链表,其中包含指向其头部和尾部的指针,可能是tail->next指向头部;为了有一个圆形清单。 问题是每当我尝试引用任何节点的指针时,我都会遇到分段错误。 我编写了一个这样的函数:

list_t * create_new_list()
{
    list_t * new_list;
    new_list->head = malloc( sizeof(node_t) );
    new_list->tail = malloc( sizeof(node_t) );

    // I've also tried
    // list * new_list = malloc( sizeof(list_t) );
    // but it doesn't work */


    /* init the head node */
    new_list->head->prev = NULL;
    new_list->head->next = NULL;
    new_list->head->key = 0;

    /* init the tail node */
    new_list->tail->prev = NULL;
    new_list->tail->next = NULL;
    new_list->tail->key = 0;

    return new_list;
}

当我从create_new_list()函数调用main()时,我得到: “分段错误。核心转储已创建”。

int main()
{
    list_t * my_list = create_new_list();

    return EXIT_SUCCESS;
}

2 个答案:

答案 0 :(得分:3)

您的问题是您永远不会为新列表分配任何内存。因此

´new_list->head = ... `

会崩溃。

尝试:

list_t * create_new_list()
{
    list_t * new_list = malloc(sizeof *new_list);  // Allocate a new list
    if (!new_list) exit(1);                        // Bail out if it failed
    new_list->head = NULL;                         // Initialize pointers
    new_list->tail = NULL;                         // Initialize pointers
    return new_list;                               // Return the new list
}

不要在create函数中分配任何节点。在insert函数中执行此操作。

类似的东西:

void insert(list_t *list, int key)
{
    node_t* new_node = malloc( sizeof *new_node );
    if (!new_node) exit(1);                        
    new_node->key = key;

    //... add the code to insert the node into the list
}

答案 1 :(得分:3)

list_t * new_list;
new_list->head = malloc( sizeof(node_t) );

由于new_list没有价值,所以这不会奏效!你也需要为它分配内存。尝试这样做

list_t * new_list = malloc(sizeof(list_t));
相关问题