我想解决的问题是:计算C代码中关键字的出现次数。这是代码:
问题是我遇到了分段错误。在我的代码中我提到了哪里 是问题。请你解释一下为什么?
标题:
struct Chei
{
char *cuv;
int contor;
};
typedef struct Chei chei;
int ReadCode(char *a[]);
void determine(chei *Ch, char *temp, int size);
void Frequency(chei *Ch, int nr_lines, char *a[], int size);
主要:
chei tab_chei[] = {{"while", 0},{"if", 0}, {"case", 0}, {"switch", 0}};
int size = sizeof(tab_chei)/sizeof(tab_chei[0]);
char *Code[MaxL];
int nr_lines;
nr_lines = ReadCode(Code);//number of lines of text
Frequency(tab_chei, nr_lines, Code, size);
在函数文件中: 我认为读取文本没有问题(函数ReadCode() - 这里我使用malloc为每个Code [i]分配了内存)。为此我使用了一个指向char的指针数组。
// This functions determines if the word "temp" is a keyword, and increases
//"contor" if it is.
void determine(chei *Ch, char *temp, int size)
{
int i;
for (i = 0; i < size; ++i)
{
if (!strcmp(Ch[i].cuv, temp))
{
Ch[i].contor++;
break;
}
}
}
数组“a”包含文本。
void Frequency(chei *Ch, int nr_lines, char *a[], int size)
{
int i;
char temp[MaxCh];
char *token = 0;
strcpy(temp, a[0]);//I put a[0] as a particular case
token = strtok(temp, " ");
determine(Ch, token, size);
while (token != NULL)
{
token = strtok(NULL, " ");
determine(ch, token, size); //here is the problem.
//I observed that if I delete this line, there is no error
//but still it isn't what I want to get
}
for (i = 0; i < size; ++i)
{
printf("\n%-10s%-4d", Ch[i].cuv, Ch[i].contor);
}
}
答案 0 :(得分:1)
我认为问题在于你没有为指针指向的每个字符串char *Code[MaxL];
分配内存。
你只为指针分配内存,你需要做类似的事情
Code[0] = calloc(0, 100);
答案 1 :(得分:1)
token = strtok(NULL, " ");
determine(ch, token, size); //here is the problem.
在将token
传递给determine()
之前,您不会检查strcmp()
。给定空指针时,{{1}}调用是未定义的行为。