我希望这个程序读取一个输入文件,然后将单个单词及其频率保存到结构中,然后将结构的内容打印到输出文件中。我正在获得分段错误,但我不知道为什么。另外我不确定我是否正确编写了程序。感谢帮助。
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct string_count
{
char *str;
int *str_freq;
};
int main(int argc, char* argv[])
{
int i=0, j, temp;
char *str_temp, *temp2;
struct string_count *word ;
FILE *fp1, *fp2;
fp1 = fopen("input.txt", "r");
if( fp1 == NULL )
{
printf("Input file can't be opened");
exit(1);
}
fp2 = fopen("output.txt", "w");
if (fp2 == NULL)
{
printf("Error: Output file can't be created");
exit (1);
}
fgets(str_temp, 50000000, fp1);
str_temp = (char*)malloc(5000000*sizeof(char));
fclose(fp1);
word->str = (char*)malloc(strlen(str_temp)*sizeof(char));
word->str_freq = (int*)malloc(strlen(str_temp)*sizeof(int));
word->str[0] = (char*)strtok(str_temp, " ,;(){}""'");
word->str_freq[0] = 0;
word->str_freq[0]++;
while(getc(fp2) != EOF)
{
i++;
word->str[i] = (char*)strtok(NULL, " ,;(){}""'");
for (j=0, word->str[i]=0;j < i;j++)
{
if( word->str[i] = word->str[j]) word->str_freq[i]++;
}
}
for (j = 1; j < i; j++)
{
if (word->str_freq[j] > word->str_freq[j - 1])
{
temp = word->str_freq[j];
word->str_freq[j] = word->str_freq[j - 1];
word->str_freq[j - 1] = temp;
str_temp = word->str[j];
word->str[j] = word->str[j - 1];
word->str[j - 1] = str_temp;
}
}
for (j = 0; j < i; j++)
{
fprintf(fp2, "%s %d\n", word->str[j], word->str_freq[j]);
}
fclose(fp2);
system("PAUSE");
}
答案 0 :(得分:0)
你先犯了这么多错误
str_temp = (char*)malloc(5000000*sizeof(char));
在之前的fgets行之前使用它,这里也是
word->str = (char*)malloc(strlen(str_temp)*sizeof(char));
这里你没有为字结构指针分配内存,并进一步向其他成员提供内存。纠正这些