我的作业有问题。任务是从txt文件中读取一个字符串,并将其与结构指针数组进行比较。如果字符串已经出现,那么将该结构的计数增加1,如果没有找到,则将该字符串插入到具有计数1的数组中。
定义结构:
struct wordfreq {
int count;
char *word;
}
以下是代码:
#include <stdio.h>
#include <stdlib.h>
struct wordfreq {
int count;
char *word;
};
typedef struct wordfreq wordfreq;
int mystrcmp(char *str1, char *str2);
int main(int argc, char *argv[])
{
int i, j, flag, current, spot;
char *temp, *temp2;
FILE *infile, *outfile;
wordfreq *wordsptr[1000];
if (argc != 3)
{
printf("Invalid number of arguments, exiting\n");
return 1;
}
else
{
infile = fopen(argv[1], "r");
outfile = fopen(argv[2], "w");
if (infile == NULL)
{
printf("Error opening input file, exiting\n");
return 2;
}
if (outfile == NULL)
{
printf("Error opening output file, exiting\n");
return 3;
}
}
current = 0;
flag = 0;
for (i = 0; i < 1000; i++)
wordsptr[i] = NULL;
temp = (char *)calloc(20,sizeof(char));
while (fgets(temp, 20, infile) != NULL)
{
flag = 0;
for (i = 0; i < 20; i++)
if (temp[i] == '\n')
temp[i] = '\0';
printf("%s %d\n", temp, current);
wordsptr[current] = (wordfreq *)malloc(sizeof(wordfreq));
wordsptr[current]->word = (char *)malloc(20*sizeof(char));
(*wordsptr[current]).word = temp;
(*wordsptr[current]).count = 1;
current++;
}
for (i = 0; i < current; i++)
printf("%d %s\n", (*wordsptr[i]).count, (*wordsptr[i]).word);
free(temp);
for (i = 0; i < 1000; i++)
{
wordsptr[i] = NULL;
free(wordsptr[i]);
}
if (infile != NULL)
fclose(infile);
if (outfile != NULL)
fclose(outfile);
return 0;
}
int mystrcmp(char *str1, char *str2)
{
int i;
for (i = 0; str1[i] != '\0' || str2[i] != '\0';i++)
if (str1[i] != str2[i])
return 1;
return 0;
}
一些规定:
1)必须将所有指针初始化为null
2)必须使用指向结构的指针数组
运行: ./assign6 words.txt freq.txt
words.txt:
apple
orange
apple
orange
banana
banana
我收到的输出: 1个香蕉 1个香蕉 1个香蕉 1个香蕉 1个香蕉 1个香蕉
它应该将txt文件中的字符串计数和字符串本身输出到argv [2]指定的文件中。请帮忙!
答案 0 :(得分:1)
您正在分配temp的地址,该地址在每次迭代时都会使用新值不断更新,因此您可以在此处获取所有结构中最后一次迭代的字符串。这是由以下几行引起的:
wordsptr[current]->word = (char *)malloc(20*sizeof(char));
(*wordsptr[current]).word = temp;
(值得一提的是,这也是内存泄漏,因为你丢失了指向堆内存的指针。)
您应该使用strcpy()
或类似的方法将字符从temp
复制到wordsptr[current]->word
。