【发布时间】:2014-01-18 23:20:25
【问题描述】:
我希望该程序读取输入文件,然后将单个单词及其频率保存到结构中,然后将结构的内容打印到输出文件中。我遇到分段错误,但我不知道为什么。另外我不确定我是否正确编写了程序。感谢您的帮助。
#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");
}
【问题讨论】:
-
你想在这里做什么? word->str[0] = (char*)strtok(str_temp, " ,;(){}""'");
-
尝试用 gdb 调试
-
不需要调试器:
word->str =字此时未初始化。 -
还有一个问题是 str_temp。你先做 fgets 然后 malloc,先做 malloc 然后 fgets
-
您在分配 str_temp 之前使用它。切换 fgets 和 malloc 语句。 stdio.h 和任何系统头文件也应该在 中。使用 == 进行比较:您正在使用 =。你的排序也不行。
标签: c segmentation-fault