[英]Dynamically Allocated Array of Pointers Keeps Rewriting Itself
我正在尝试编写一个程序,使用动态分配的指针数组来查找文件(words.txt)中单词的频率,以存储单词和单词出现的频率,并将结果打印到另一个文件(频率)。文本)。
例:
从word.txt中读取
apple
orange
apple
banana
orange
apple
写入frequencys.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;
}
现在,我只是尝试获取分配的第一个值(一个苹果)。 我遇到的问题是,当我尝试分配动态数组的第一个值时,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 = strdup(buffer)
替换wordarray[0]->word = buffer
当前wordarray[0]->word
是指向buffer
的指针,因此,每当您运行fscanf(fp,"%s",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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.