Applepine Applepine - 6 days ago 7
C++ Question

Getting stuck in Dictionary Project in C

I prefer to create a

Dictionary
object and add 3 words to it.
My program has no compilation error but gets a run time error in the second for loop, is the problem in
addNewWord
function? Do I need pass a pointer to the
DictionaryWord
object ?

Please help me.

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

typedef struct{
char* name;
char* mean;
} Words;

typedef struct{
Words* word;
int size;
} Dictionary;

Dictionary createNewDictionary();
Words createNewWord();
void addNewWord(Words newword, Dictionary dic);

Dictionary createNewDictionary(){
Dictionary dic;
dic.size = 0;
dic.word = (Words*)malloc(dic.size*sizeof(Words));
return dic;
}

Words createNewWord(){
Words newword;
newword.name = (char*)malloc(30*sizeof(char));
newword.mean = (char*)malloc(30*sizeof(char));
printf("============================\n");
printf("Enter word: ");
scanf("%[^\n]", newword.name);
fflush(stdin);
printf("\nEnter meaning: ");
scanf("%[^\n]", newword.mean);
return newword;
}

void addNewWord(Words newword, Dictionary dic){
dic.size++;
dic.word = (Words*)realloc(dic.word,dic.size*sizeof(Words));
strcpy(dic.word[dic.size-1].name, newword.name);
strcpy(dic.word[dic.size-1].mean, newword.mean);
}

int main(){
Dictionary d = createNewDictionary();
for (int i=0;i<3;i++){
addNewWord(createNewWord(), d);
}
return 0;
}

Answer

I see what's wrong with your code. First of all, you need to pass your Dictionary object by pointer to the function, addNewWord, and in the function addNewWord, you again need to allocate memory to each of the char* fields, name and mean, of the dic object. Here is the corrected code :

void addNewWord(Words newword, Dictionary *dic){
    dic->size++;
    dic->word = (Words*)realloc(dic->word, dic->size*sizeof(Words));
    dic->word[dic->size-1].name = (char*)malloc(30*sizeof(char));  //added
    dic->word[dic->size-1].mean = (char*)malloc(30*sizeof(char));  //added
    strcpy(dic->word[dic->size-1].name, newword.name);
    strcpy(dic->word[dic->size-1].mean, newword.mean);
}

Pass the dictionary's address as :

addNewWord(createNewWord(), &d);

and change the definition as well as prototype of the function as well :

void addNewWord(Words newword, Dictionary *dic)

Find the complete code here : http://pastebin.com/ZN69hevj

Comments