ShadyBears
ShadyBears

Reputation: 4185

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

Upvotes: 2

Views: 3072

Answers (2)

unxnut
unxnut

Reputation: 8839

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.

Upvotes: 5

luser droog
luser droog

Reputation: 19504

For a linked-list, you typically have a link to the next node in the node structure itself.

typedef struct node
{
    char letter;
    struct node *next;
}NODE;

Then from any given node NODE *n, the next node is n->next (if not NULL).

insert should scan the list until it finds an n->next that is NULL, and allocate a new node at the end (make sure to set its next to NULL).

You may want to have a function to initialize a new list given the table index, and a separate function to initialize a new node.

Upvotes: 4

Related Questions