In the following code, I'm trying to make a global array of struct called myArray
then call create()
inside main()
which makes a local array of struct and fill it with data then assign the first element's address of the local array to the global pointer.
But when I try to print myArray
elements one by one it shows garbage strings, why? and how can I solve it? also if there are any improvements to my code please let me know them.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct HashNode
{
char Word[MAX_WORD_SIZE];
char Meanings[MAX_MEANINGS_SIZE];
char Synonyms[MAX_SYNONYMS_SIZE];
char Antonyms[MAX_ANTONYMS_SIZE];
};
//Global pointer to an array of struct
struct HashNode *myArray;
int main()
{
create();
for(int i = 0; i < 100; i++)
puts(myArray[i].Word);
}
void create()
{
struct HashNode HashDictionary[100];
for(int i = 0; i < 100; i++)
{
strcpy(HashDictionary[i].Word, "");
strcpy(HashDictionary[i].Meanings, "");
strcpy(HashDictionary[i].Synonyms, "");
strcpy(HashDictionary[i].Antonyms, "");
}
strcpy(HashDictionary[1].Word, "Word");
strcpy(HashDictionary[1].Meanings, "Meanings");
strcpy(HashDictionary[1].Synonyms, "Synonyms");
strcpy(HashDictionary[1].Antonyms, "Antonyms");
myArray = &HashDictionary[0];
}