Contents
  1. 1. 此文是对上篇文章的一点补充

此文是对上篇文章的一点补充

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46


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

struct node{
int age;
char name[10];
};

struct Node{
double data;
int other;
}s[100];

struct str{
int data;
char str[100];
}string[100];

int cmpstruct2(const void *a, const void *b)
{

return (*(struct Node *)a).data > (*(struct Node *)b).data ? 1 : -1;
} //return ((struct Node *)a)->date > ((struct Node *)b)->date ? 1 : -1;
//这样也行, 那两对括号一定要加上

//对结构体二级排序
//先对年龄排序,年龄相同再按姓名排序。
int cmpstruct1(const void *a, const void *b)
{

//先作下指针转换,再按要求比较
struct node *pnode1 = (struct node *)a;
struct node *pnode2 = (struct node *)b;
if(pnode1->age != pnode2->age)
return pnode1->age - pnode2->age;
else
return strcmp(pnode1->name, pnode2->name);
}

//对字符串进行排序
//按照结构体中字符串str的字典顺序排序
int cmpstr(const void *a, const void *b)
{

return strcmp((*(struct str *)a)->str, (*(struct str *)b)->str);
}
Contents
  1. 1. 此文是对上篇文章的一点补充