Search code examples
clinked-listdynamic-programming

Need help printing a dynamically allocated linked list in C


typedef struct Word {
    char** translations;
    struct Word* next;
} Word;

typedef struct {
    char** languages;
    int numOfLanguages;
    Word* wordList;
} Dictionary;

void printWordList(Word* wordlist, int numOfLanguages)
{
    Word* currentWord = wordlist;
    int i = 0;
    while (currentWord != NULL)
    {
        for (i=0; i < numOfLanguages; i++)
        {
            printf("%s", currentWord->translations[i]);
            if (i < numOfLanguages - 1)
                putchar(',');
        }
        putchar('\n');
        currentWord = currentWord->next;
    }
    putchar('\n');
}

Hey, I have a program that's a dynamically allocated dictionary that works like this:

Choose a dictionary:

  1. English,Spanish,French

  2. English,Hebrew

  3. Spanish,English

    1
    

Enter a word in English,Spanish,French:

Thank_you,Gracias,Merci

The word has been added successfully!

Later I use the function above, printWordList, to try and print all the words (and their translations, Thank_you,Gracias,Merci counts as one, with Gracias and Mercy being in the translations array)

The function works perfectly when there's only one word and translations, but if I add another word to the list, it enters an endless loop and still only prints the first word.


Solution

  • As it is, the printWordList function you posted above will not go for endless loop, unless you made a mistake in filling the next value for the last node.