Applepine Applepine - 3 months ago 39
C++ Question

Getting stuck in Dictionary Project in C

I prefer to create a

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
function? Do I need pass a pointer to the
object ?

Please help me.


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; = (char*)malloc(30*sizeof(char));
newword.mean = (char*)malloc(30*sizeof(char));
printf("Enter word: ");
printf("\nEnter meaning: ");
scanf("%[^\n]", newword.mean);
return newword;

void addNewWord(Words newword, Dictionary dic){
dic.word = (Words*)realloc(dic.word,dic.size*sizeof(Words));
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;


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->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].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 :