我写了一个程序,可以从文本文件中读取单词。每行有一个单词。我需要找到每个单词重复的次数。到目前为止,为了找出这一点,我已经从文件中读取了单词,并将它们全部放在动态分配的结构数组中。我的问题是,每当我尝试运行它时,该程序都会出现分段错误。我认为动态分配数据的方式存在问题。代码如下;
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
//struct
struct _data {
char *word;
int number;
};
//scan for size of file
int SCAN(FILE *data) {
int size = 0;
char s_temp[50];
while (1) {
fscanf(data, "%s", s_temp);
if (feof(data)) break;
size++;
}
return size;
}
//load content into struct
int LOAD(FILE *data, int size, struct _data *Wordstruct){
int i;
char temp[50];
for (i=0; i <size; i++){
fscanf(data, "%s", temp , &Wordstruct[i].word, &Wordstruct[i].number);
Wordstruct[i].word =calloc(strlen(temp), sizeof(char));
strcpy(Wordstruct[i].word, temp);
if(strcasecmp(Wordstruct[i].word, temp) ==0){
Wordstruct[i].number++;
}
}
return size;
}
//count how many times each word repeats
void COUNT(struct _data *Wordstruct, int size){
int i;
int count;
count =0;
char *word;
if (strcasecmp(Wordstruct[i].word, word)==0){
count++;
for(i=0; i<size; i++){
printf("%sn",Wordstruct[i].word,"occurs:t",count);
}
}
}
//main routine
int main(int argc, char *argv[]){
int size;
FILE *data;
struct _data *Wordlist;
if(argc <2){
printf("Not enough argumentsn");
}
else{
FILE *data= fopen(argv[1],"r");
size =SCAN(data);
LOAD(data, size, Wordlist);
COUNT(Wordlist, size);
}
return 0;
}
您尚未为 Wordlist
分配内存。加
Wordlist = malloc(size*sizeof(*Wordlist));
在打电话给LOAD
之前。
而且,正如@BLUEPIXY在评论中指出的那样,改变
Wordstruct[i].word =calloc(strlen(temp), sizeof(char));
自
Wordstruct[i].word =calloc(strlen(temp)+1, sizeof(char));
更改 以下内容:
Wordstruct[i].word =calloc(strlen(temp), sizeof(char));
对此:
Wordstruct[i].word =calloc(strlen(temp)+1, sizeof(char));
您需要考虑 NULL 终止符,strlen()
在这里不会为您执行此操作。