c - 段错误和结构

标签 c segmentation-fault

我希望该程序读取输入文件,然后将单个单词及其频率保存到结构中,然后将该结构的内容打印到输出文件中。我遇到段错误,但我不知道为什么。我也不确定我的程序是否正确编写。感谢您的帮助。

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

最佳答案

你首先在这里犯了很多错误

str_temp = (char*)malloc(5000000*sizeof(char));

在 fgets 行之前和这里也使用它

word->str = (char*)malloc(strlen(str_temp)*sizeof(char));

这里您还没有为字结构指针分配内存并进一步将内存分配给其其他成员。纠正这些

关于c - 段错误和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20867219/

相关文章:

C——编译没有错误但函数不起作用

python - 单元测试 C 生成 python 代码

从另一个文件调用#define

c - 缩放互补误差函数的精确计算,erfcx()

c - 出现段错误 11 不确定在 C 中是否正确使用指针

c - 在 C 中将结构传递给回调时出现 SIGSEGV(段错误)

c - 为结构体 "error"分配内存

C - 释放动态分配的数组后出现段错误

c - fwrite 段错误 - 大小为 4 的无效读取

c - 为什么在为矩阵分配内存时会出现段错误?