我正在编写一个程序,用于计算每个单词在文本文件中出现的次数。我收到一个运行时错误:段错误(核心已转储)。我知道这与尝试访问尚未分配的内存有关。
另外,我收到关于我对 getline 的争论的警告,我不确定我是否正确使用它。任何建议表示赞赏。
我的代码是:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define MAXWORDS 5000
#define MAXLINE 1000
#define MAXWORDLEN 100
int count = 0;
struct wordcount *wordPtr[MAXWORDS];
typedef struct wordcount *wordcountptr;
typedef struct wordcount {
char word[50];
int count;
} wordcount_t;
main()
{
int wordfound = 0;
int len;
char line[MAXLINE];
int printcount;
while ((len = getline(line, MAXLINE, stdin))> 0)
{
int i = 0;
int j = 0;
for( ; i<len; i++)
{
if(line[i] != isalnum(line[i]) && line[i] != 32)
line[i] = 32;
else
line[i] = tolower(line[i]);
}
for( ; j<len; j++)
{
char currentword[MAXWORDLEN];
if(line[j] != 32)
{
for(i=0; line[j] != 32; i++)
currentword[i] = line[j];
}
if(line[j] == 32)
{
for(i=0;i<MAXWORDS; i++)
{
if(strcmp(currentword, (*wordPtr[i]).word) == 0)
{
(*wordPtr[i]).count++;
wordfound = 1;
}
}
if(wordfound == 0)
{
wordPtr[i] = (wordcount_t*)malloc(sizeof(wordcount_t));
strcpy((*wordPtr[i]).word, currentword);
(*wordPtr[i]).count = 1;
count++;
}
}
wordfound = 0;
}
}
for(printcount = 0; printcount < count; printcount++)
printf("There are %d occurances of the word %s\n", (*wordPtr[printcount]).count, (*wordPtr[printcount]).word);
for(printcount = 0; printcount < MAXWORDS; printcount++)
{
free((void*)wordPtr[printcount]);
wordPtr[printcount]= NULL;
}
}
最佳答案
getline()
期望第一个参数是 char **
类型,因此您应该这样调用它:
getline(&line, MAXLINE, stdin)
因为line
是一个char数组,所以相当于char *
而不是需要的char **
。
引自this SO answer使用 char **
而不是 char *
的原因是:
You need to pass in a char** (ie a pointer to a pointer to a char) so that the function is able to update the value of the char* that it points to.
关于c - 段错误(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20368607/