简体   繁体   中英

Array of linked lists in C

I'm having difficulties on making an array of linked lists. I have this struct

typedef struct node {
    int id;
    struct node * next;
} t_point;

t_point* array[10];

and I want, for example, that array[0] points to the head of a linked list, and then fill with, repeating this process to all spaces of the array

I understand how I need to code it, but I can't get it right. I just want someone to show me and explain me the syntax.

Something like this:

t_point* array[10]

void link_list()
{
    int array_length = sizeof(array) / sizeof(t_point*);

    // Allocate the memory for the first list item
    array[0] = malloc(sizeof(t_point));

    // Iterate through each item in `array` and allocate it some memory
    for (int i = 1; i < array_length; i++)
    {
        // Allocate memory for the next item
        array[i] = malloc(sizeof(t_point));

        // Set the previous item's `next` field to the current item pointed to by `i`
        array[i - 1]->next = array[i];
    }

    // Close the list by adding a NULL pointer
    array[array_length - 1]->next = NULL;
}

Also remember to free the malloc 'ed memory otherwise you will get memory leaks. I'll leave that up to you.

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