简体   繁体   中英

How do I refer to pointers in nested structs?

I'm fairly new to C pointers so I'm trying to play around with them to figure out how they work, more in depth. I've got the following data types, defined with 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;

My goal is to have a doubly linked list with a pointer to its head and its tail, maybe with tail->next pointing to the head; in order to have a circular list. The problem is that whenever I try to refer to any of the node's pointers, I get a segmentation fault. I coded a function like this:

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;
}

When I call create_new_list() from my main() function I get: "Segmentation Fault. Core dump created".

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

    return EXIT_SUCCESS;
}

Your problem is that you never allocate any memory for the new list. Consequently

´new_list->head = ... `

will crash.

Try:

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
}

Don't allocate any nodes in the create function. Do that in an insert function.

Something like:

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
}
list_t * new_list;
new_list->head = malloc( sizeof(node_t) );

This won't work as new_list doesn't have a value! You need to allocate memory for it as well. Try doing this

list_t * new_list = malloc(sizeof(list_t));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM