gpt4 book ai didi

c - 在整数数组上实现 qsort 时遇到问题,无法处理超过 6 个数字的数组

转载 作者:行者123 更新时间:2023-11-30 17:04:51 24 4
gpt4 key购买 nike

在练习中,我们的讲师让我们实现一些排序方法。其中两个是我们自己构建的,我做得很好,讲师给了我们 qsort 的代码,如下所示:

#include <stdio.h>
#include <stdlib.h>

//Your comparison function, here comparing "short" type data.
int larger_than(const void* left, const void* right) {
short* left_s = (short*) left;
short* right_s = (short*) right;

return *left_s > *right_s;
}

int main() {

int item_count = 5;

short* array = calloc(item_count, sizeof(short));


array[0] = 4;

array[1] = 0;

array[2] = 1;

array[3] = 13;

array[4] = 4;


qsort(array, item_count, sizeof(short), larger_than);

//Name of your comparison function --------^


printf("%d %d %d %d %d\n", array[0], array[1], array[2], array[3], array[4]);


free(array);


return 0;
}

因此,我们必须对其进行调整以对整数数组进行排序,并且不要手动填充数组,而是在标准输入中指定数组长度以及填充数组的整数。所以我的代码如下所示:

#include <stdio.h>
#include <stdlib.h>

int larger_than(const void* left, const void* right) {

int* left_s = (int*) left;

int* right_s = (int*) right;


return *left_s > *right_s;
}

void print_array(int* data_array, int array_length) {
int counter = 0;
while (counter != array_length) {
printf("%d ", data_array[counter]);
counter = counter + 1;
}
}

int main() {

int input_size;
int data_item;
scanf("%d", &input_size);
int* data_array = calloc(input_size, sizeof(int));
int counter = 0;
while (counter != input_size) {
scanf("%d", &data_item);
data_array[counter] = data_item;
counter = counter + 1;
}

qsort(data_array, input_size, sizeof(int), larger_than);

print_array(data_array, input_size);

free(data_array);

return 0;
}

我最初使用在线 IDE (ideone),它编译得很好,并给出了正确的排序结果。然后我用 GCC 进行编译,发现它给了我一个错误的排序。所以现在我正在尝试找出我的代码出了什么问题。例如,如果我给我的程序这个输入:

7
7 6 5 4 3 2 1

返回

4 3 2 1 5 6 7

而不是

1 2 3 4 5 6 7

我做了一些更多的测试,发现了一些非常奇怪的东西,如果我给它 6 个数字,它会很好地排序,但是任何超过 6 个数字都会给我一个完全错误的结果。我对 C 很陌生,所以我一直在查看我的代码,但我一生都无法弄清楚我做错了什么。有什么建议吗?

最佳答案

如果第一个参数更大,则自定义比较函数返回 1;如果两个参数相等或第二个参数较大,则为 0。

将其与比较函数应该返回的内容进行比较(来自 man qsort):

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

如果这确实来自您的教授,您应该让他或她参阅联机帮助页。

关于c - 在整数数组上实现 qsort 时遇到问题,无法处理超过 6 个数字的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544447/

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