gpt4 book ai didi

c - strncmp() 在我的快速排序 c 编程中给出 Segmentation Fault 11

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:37 26 4
gpt4 key购买 nike

我的 strncmp() 函数出现段错误 11。我知道错误在哪里,但不知道是什么原因造成的。这就是我要解决的问题。我输入了一个包含很多单词的txt文件。然后我需要计算每个单词的频率然后对单词进行排序。最后,输出排序后的单词及其频率。所以由于它是一个 C 程序,我使用链表来存储单词和频率。将单词添加到链表和计算每个单词的频率都很好。该错误发生在我用来对单词进行排序的快速排序中。我的快速排序:

struct node *quick_sort(struct node *head, int l, int r){
int i, j;
int jval;
int pivot;
int min;
char* test1;
char* test2;
i = l + 1;
if (l + 1 < r) {
test1 = get_char(head, l);
pivot = get_freq(head, l);
for (j = l + 1; j <= r; j++) {
jval = get_freq(head, j);
test2 = get_char(head, j);
printf("test 1: %s test 2: %s\n",test1,test2);
min = strlen(test1) < strlen(test2) ? strlen(test1) : strlen(test2);
printf("Length 1 :%ld Length 2: %ld Max is: %d\n",strlen(test1),strlen(test2), min);

// HERE is where the bug is
if (strncmp(test2,test1,min)<0 && jval != -1) {
swap(head, i, j);
i++;
}
}
swap(head, i - 1, l);
quick_sort(head, l, i);
quick_sort(head, i, r);
}

return head;
}

和其他相关函数:

int get_freq(struct node *head, int l){
while(head && l) {
head = head->next;
l--;
}
if (head != NULL)
return head->freq;
else
return -1;
}

void swap(struct node *head, int i, int j){
struct node *tmp = head;
int tmpival;
int tmpjval;
char* tmpiStr;
char* tmpjStr;

int ti = i;
while(tmp && i) {
i--;
tmp = tmp->next;
}
tmpival = tmp->freq;
tmpiStr = tmp->str;
tmp = head;
while(tmp && j) {
j--;
tmp = tmp->next;
}
tmpjval = tmp->freq;
tmpjStr = tmp->str;
tmp->freq = tmpival;
tmp->str = tmpiStr;
tmp = head;
i = ti;
while(tmp && i) {
i--;
tmp = tmp->next;
}
tmp->freq = tmpjval;
tmp->str = tmpjStr;
}

char* get_char(struct node *head, int l){
char* res;
while(head && l) {
head = head->next;
l--;
}
if (head != NULL){
char * arr = head->str;
return arr;
}
else
return res;
}

如果我更改 strncmp() 中的最小值,有时程序会运行。我不知道出了什么问题。提前致谢。

最佳答案

您永远不会在这一行的 get_char 函数中声明的变量赋值

char* res;

Segmentation fault 11 错误通常在程序访问尚未分配的内存时被调用。在您的情况下,您可能正在尝试比较字符串和内存中的某个随机位置。

关于c - strncmp() 在我的快速排序 c 编程中给出 Segmentation Fault 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15776631/

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