Complementary task for topic: 7

M Nemeth � 2023-08-29 15:21:04.625218'

DStrings+Struct: Simple Dictionary 2.

DStrings+Struct: Simple Dictionary 2.

Main goal:
Create a C program that simulates a simple dictionary application. The program should allow the user to add new words and their meanings to the dictionary and search for the meanings of existing words. The word and its meaning will be stored as dynamic strings in a dynamic structure using dynamic memory allocation.
First task:
> Create an addWord function that gets the dictionary (and the size of course!) and add one new word to it. You can use the realloc. Keep in mind, you need to edit things out of the function. The word is read from consol inside the function.
> Use the above mentioned function in main to try it out, add two word into the dictionary
> print out the words contained by the dictionary in main!

Hint: > If you need to edit something that is not in the function, you have to pass by its address. Here the pointer that helds the dictinary may change (realloc), so the pointer must be passed by address. The size also changes.
> There is no way to know the size of a string before it is typed. So we need to read it charcter by character!

Solution
#include 
#include 
#include 
 
typedef struct {
    char* word;
    char* meaning;
} DictionaryEntry;
 
void clearInputBuffer() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF) {}
}
 
void addWord(DictionaryEntry** dictionary, int* wordCount) {
    DictionaryEntry newWord;
 
    printf("Enter the word: ");
 
    //scanf("%s", &newWord.word); Will not work! try out!
    //Dynamic read is complicated
    char c=getchar();
    int size=1;
    char* str=(char*)malloc(size*sizeof(char));
    str[0]='\0';
    while(c!='\n'){
 
        str=(char*)realloc(str,++size*sizeof(char));
        str[size-2]=c;
        str[size-1]='\0';
        c=getchar();
    }
    newWord.word=str;
 
    printf("Enter the meaning: ");
    //scanf("%s", &newWord.meaning); Will not work! try out!
    c=getchar();
    size=1;
    str=(char*)malloc(size*sizeof(char));
    str[0]='\0';
    while(c!='\n'){
 
        str=(char*)realloc(str,++size*sizeof(char));
        str[size-2]=c;
        str[size-1]='\0';
        c=getchar();
    }
    newWord.meaning=str;
 
    (*wordCount)++;
    *dictionary = (DictionaryEntry*)realloc(*dictionary, (*wordCount) * sizeof(DictionaryEntry));
    (*dictionary)[*wordCount - 1] = newWord;
 
    printf("Word added successfully!\n");
}
 
int main() {
    int wordCount = 0;
    DictionaryEntry* dictionary = NULL;
    char searchWord[100]; /to read the word...
    addWord(&dictionary, &wordCount);
    addWord(&dictionary, &wordCount);
    for(int i=0;iprintf("%s",dictionary[i].word);="" return="" 0;="" }="" <="" code="">

Explanation
use the hint!
< < previous    next > >