动态分配的指针数组不断重写自身

Dynamically Allocated Array of Pointers Keeps Rewriting Itself

我正在尝试编写一个程序来查找文件中单词的频率 (words.txt),使用动态分配的指针数组来存储单词和 单词出现的频率并将结果打印到另一个文件 (frequencies.txt)。

示例:

阅读自words.txt

apple
orange
apple
banana
orange
apple

写入frequencies.txt:

3 apple
2 orange
1 banana

这是程序

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

struct wordfreq 
{
  int count;
  char *word;
};

typedef struct wordfreq wordfreq;

int main(int argc, char *argv[])
{
    wordfreq **wordarray;
    int size = 1, i, j, x, compare;
    char buffer[100];
    FILE *fp;

    if ( argc != 3 )
    {
        fprintf(stderr,"!!!ERROR!!!\nNUMBER OF MISSING PARAMETERS: %d\n", 3-argc);
        exit(-1);
    }

    fp = fopen(argv[1],"r");
    if ( fp == NULL )
    {
        perror(argv[1]);
        exit(-1);
    }

    wordarray = (wordfreq**)malloc(size*sizeof(wordfreq*));

    for(i = 0; i < size; i++)
    {
        wordarray[i] = (wordfreq *) malloc(sizeof(wordfreq*));
        wordarray[i]->word = "!";
        wordarray[i]->count = 0;
    }

    while(fscanf(fp,"%s",buffer) == 1)
    {
        printf("Word: %s\n", buffer);

        if(wordarray[0]->word == "!")
        {
            wordarray[0]->word = buffer;
            wordarray[0]->count = 1;
        }

        //Continued coding

        for(x = 0; x < size; x++)
        {
            printf("%d %s\n", wordarray[x]->count, wordarray[x]->word);
        }
        printf("\n");
    }

    //wordarray = realloc(wordarray,size*sizeof(wordfreq*));

    fclose(fp);

    fp = fopen(argv[2], "w");
    if ( fp == NULL )
    {
        perror(argv[1]);
        exit(-1);
    }

    for(i = 0; i < size; i++)
    {
        fprintf(fp, "%d %s\n", wordarray[i]->count, wordarray[i]->word);
    }

    fclose(fp);

    free(wordarray);

    return 0;
}

现在我只是试图获得分配的第一个值(1 个苹果)。我遇到的问题是,当我尝试分配动态数组的第一个值时,wordarray->word 的值会随着每次从文件中读取而改变,但它应该保持为 apple:

Word: apple
1 apple

Word: orange
1 orange

Word: apple
1 apple

Word: banana
1 banana

Word: orange
1 orange

Word: apple
1 apple

Results:
1 apple

如有任何建议,我们将不胜感激。

wordarray[0]->word = buffer替换为wordarray[0]->word = strdup(buffer)

当前 wordarray[0]->word 是指向 buffer 的指针,因此每次 运行 行 fscanf(fp,"%s",buffer) 都会更改它的值

** 最后不要忘记释放 strdup 内存

for(i = 0; i < size; i++)
{
    free(wordarray[i]->word);
}

还有,你不知道size是什么。首先,您可以扫描文件并找出大小:

int size = 0;
while (!feof(fp))
{
    fscanf(fp, "%s\n", buffer);
    size++; //you have this many lines in the files
}
rewind(fp);