gpt4 book ai didi

c - 奇怪的分段默认

转载 作者:太空宇宙 更新时间:2023-11-04 02:42:42 25 4
gpt4 key购买 nike

我要解决的问题是:统计一段C代码中关键字出现的次数。这是代码:

The problem is that I get a segmentation fault. In my code I mentioned where is the problem. Can you, please, explain me why ?

在标题中:

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

}

最佳答案

token = strtok(NULL, " ");
determine(ch, token, size); //here is the problem.

在将 token 传递给 determine() 之前,您没有检查它。当给定空指针时,strcmp() 调用是未定义的行为。

关于c - 奇怪的分段默认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30223476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com