用qsort对指针数组进行排序,失败了,帮忙看看

Longerandlonger Longerandlonger 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

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

#define SZ 10

typedef struct node
{
unsigned long id; // 排序时,要根据结构体的id进行排序
} node;

int cmp(const void* pn1, const void* pn2); // 比较函数

int main(int argc, char* argv[])
{
int nLoop = 0;
node* Array[SZ];

srand(time(NULL));
for(nLoop = 0; nLoop < SZ; ++nLoop)
{
Array[nLoop] = malloc(sizeof(node));
Array[nLoop]->id = rand();
printf("%d ", (Array[nLoop])->id );
}
printf("\n\n");

qsort(Array, SZ, sizeof(node*), cmp);

for(nLoop = 0; nLoop < SZ; ++nLoop)
{
printf("%d ", (Array[nLoop])->id );
}
printf("\n\n");

return 0;
}

int cmp(const void* pn1, const void* pn2) // 比较函数
{
const node* p1 = pn1;
const node* p2 = pn2;
int val;
if(p1->id < p2->id)
{
val = -1;
}
else if (p1->id == p2->id)
{
val = 0;
}
else
{
val = 1;
}
return val;
}
...全文
评论 12
收藏 已收藏
分享
返回顶部
Longerandlonger
C语言 70,039 成员 243,237 内容