Search code examples
arrayscstructdynamic-memory-allocationc-strings

Struct array in c gives the same value to all values. [C]


I read words from the file. When I throw them into the structure, it writes the same values. What is Problem and How can I fix

  1. Ide: VsCode
  2. Compiler: mingw64-gcc-g++

File Content;

{Sam} 
{Patrick} 
{Philips}

My Code;

struct Sentence
{
    char *word;
};

struct Sentence *words[20];

void readFile(const char *path, char *fileName)
{
    int wordpointer = 0;
    int len = strlen(fileName);
    FILE *fp;
    if ((fp = fopen((path), "r")) != NULL)
    {
        char ch = fgetc(fp);
        while (ch != EOF)
        {
            if (ch == '{')
            {
                int counter = 0;
                while (ch != EOF)
                {
                    char word[20];
                    ch = fgetc(fp);
                    if (ch == '}')
                    {
                        //printf("%s\n",word);
                        struct Sentence *st = malloc(sizeof(struct Sentence));
                        st->word = word;
                        words[wordpointer] = st;
                        wordpointer++;
                        break;
                    }
                    word[counter++] = ch;
                }
            }
            ch = fgetc(fp);
        }
        fclose(fp);
    }
    for (int i = 0; i < wordpointer; i++)
        printf("%s\n", words[i]->word);
}

I can get proper output in the printf function in the comment line, but when I print the Struct, all the values ​​as below are the last word in the file.

Output;

Philips
Philips
Philips

Solution

  • In this while loop

                while (ch != EOF)
                {
                    char word[20];
                    //...
    

    all pointers st->word = word; points to the same local variable word

                    if (ch == '}')
                    {
                        //printf("%s\n",word);
                        struct Sentence *st = malloc(sizeof(struct Sentence));
                        st->word = word;
                        words[wordpointer] = st;
                        wordpointer++;
                        break;
                    }
    

    declared like

    st->word = word;
    

    So after exiting the while loop the pointers will be invalid.

    You need to allocate memory for each string and copy there entered strings. Moreover you need to append them with the terminating zero character '\0'.