动态分配的指针数组保持自我重写

时间:2015-04-19 06:19:19

标签: c string pointers structure

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

示例:

阅读words.txt

apple
orange
apple
banana
orange
apple

写入频率.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-&gt; 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

感谢任何建议。

2 个答案:

答案 0 :(得分:0)

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);
}

答案 1 :(得分:0)

另外,你不知道size是什么。首先,您可以扫描文件并找出尺寸:

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