gpt4 book ai didi

c - 使用 qsort 函数

转载 作者:行者123 更新时间:2023-11-30 21:25:36 24 4
gpt4 key购买 nike

C 有一个名为 qsort 的内置函数。我已经用谷歌搜索了如何在程序中使用这个函数,但我无法完全理解它。有人可以用简单的语言向我解释一下其中涉及的变量及其具体用途吗?谢谢!

最佳答案

C 库函数 void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) 对数组进行排序。

以下是 qsort() 函数的声明。

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*));

base——这是指向要排序的数组的第一个元素的指针。

nitems——这是base指向的数组中元素的数量。

size——这是数组中每个元素的大小(以字节为单位)。

compar——这是比较两个元素的函数。

以下示例显示了 qsort() 函数的用法。

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

int values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}

int main()
{
int n;

printf("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}

qsort(values, 5, sizeof(int), cmpfunc);

printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}

return(0);
}

关于c - 使用 qsort 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28642378/

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