【问题标题】:qsort won't sort an array of integersqsort 不会对整数数组进行排序
【发布时间】:2021-06-23 16:44:25
【问题描述】:

这是我的代码:

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

int comp (const void *a, const void *b)
{
    int *s1 = (int *)a;
    int *s2 = (int *)b;

    return (s1 - s2);
}

int main() {
    int a[] = { 1, 2, 5, 3 };
    qsort(a, 4, sizeof(a), comp);
    for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++) {
        printf("%d ", a[i]);
    }
}

我正在使用qsort() 对我的数组进行升序排序,但不幸的是,没有任何反应。数组元素保持在相同的位置。每当调用 comp() 函数时,我都尝试打印消息,并且它被正确调用。问题是,元素没有改变。

可能是什么问题?

【问题讨论】:

  • 你减去的是指针,而不是整数。引用指针以获取实际值。
  • 它会很好地按内存中的位置对它们进行排序 :) 哦,好吧,它们已经按那个排序了……
  • @ChristopherMoore 你的意思是return (*s1 - *s2)?
  • 顺便说一句,这是一个危险的功能。它可以溢出int。您最好使用比较并根据它返回+/-10
  • qsort() 参数sizeof(a) 也是错误的,应该是sizeof a[0](每个元素的大小)。

标签: arrays c qsort


【解决方案1】:

你减去的是指针,而不是整数。引用指针以获取实际值。

这可能意味着像你说的那样做return (*s1 - *s2)。然而,正如 Eugene Sh.提到,这可能会溢出int。所以改为比较 *s1*s2 并相应地返回 1-10。 Weather Vane 还提到您传递了错误的尺寸值。您应该将元素的数量和每个元素的大小分别传递给第二个和第三个参数。 所以qsort(a, sizeof(a)/sizeof(a[0]), sizeof(a[0]), comp);

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

int comp (const void * a, const void * b)
{
    int *s1 = (int *)a;
    int *s2 = (int *)b;

    if(*s1 > *s2) {
        return 1;
    }
    else if(*s1 == *s2) {
        return 0;
    }
    else {
        return -1;
    }
}

int main() {
    int a[] = {1, 2, 5, 3};
    qsort(a, sizeof(a)/sizeof(a[0]), sizeof(a[0]), comp);
    for (int i = 0; i<sizeof(a)/sizeof(a[0]); i++) {
        printf("%d ", a[i]);
    }
}

【讨论】:

  • 次要:代码可能会丢失一些 (): sizeof(a)/sizeof(a[0]) --> sizeof a/sizeof a[0]int i = 0size_t i = 0 更好
猜你喜欢
  • 1970-01-01
  • 2019-05-23
  • 1970-01-01
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
相关资源
最近更新 更多