1

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];
}
Balawi28
  • 119
  • 7
  • `struct HashNode HashDictionary[100];` is a local array, so after the function which defines it has returned, that array no longer exists. Please see [Function returning address of local variable error in C](https://stackoverflow.com/questions/22288871/function-returning-address-of-local-variable-error-in-c) – Weather Vane Dec 24 '20 at 18:27
  • Thanks, It's the first time I know this. – Balawi28 Dec 24 '20 at 18:31

0 Answers0