Search code examples
clinked-listdynamic-arrays

Dynamic array of linked lists in C


Basically I have to store words in linked list with each character having its own node. I get really confused with nested structures. How do I go to the next node? I know i'm doing this completely wrong which is why I'm asking.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
    char letter;
}NODE;


typedef struct handle
{
    NODE **arr;
}HANDLE;

HANDLE * create();


void insert(handle **, char, int);

int main(int argc, char **argv)
{
    FILE *myFile;
    HANDLE *table = (HANDLE *)malloc(sizeof(HANDLE));
    NODE *linked = (NODE *)malloc(sizeof(NODE));
    int counter = 0;

    linked = NULL;
    table->arr[0] = linked;

    char c;


    myFile = fopen(argv[argc], "r");

    while((c = fgetc(myFile)) != EOF)
    { 
        if(c != '\n')
            insert(&table, c, counter);

        else
        {
            counter++;
            continue;
        }
    }
}


void insert(HANDLE **table, char c, int x)
{
    (*table)->arr[x]->letter = c; //confused on what to do after this or if this
                                  //is even correct...
} 

Solution

  • You have a linked list of words with each word being a linked list of characters. Am I right? If so, it is better to use the names for what they are:

    typedef struct char_list
    {
        char                    letter;
        struct char_list      * next;
    } word_t;
    
    typedef struct word_list
    {
        word_t                * word;
        struct word_list_t    * next;
    } word_list_t;
    

    Now, you can populate the lists as per need.