// 架构提定义:
struct MyStruct
{
int begin;
int end;
}StructArray[3]; //define a struct array length is 3.
结构体CMP函数:
int structCmp(const void* e1,const void* e2)
{
struct MyStruct* aa = (struct MyStruct*)e1; //强制转换为所定义结构体类型
struct MyStruct* bb = (struct MyStruct*)e2;//强制转换为所定义结构体类型
return aa->begin - bb->begin;//选择结构体之内的排序字段
}
int main()
{
//初始化结构体
StructArray[0].begin = 10;
StructArray[0].end = 1;
StructArray[1].begin = 80;
StructArray[1].end = 50;
StructArray[2].begin = 30;
StructArray[2].end = 100;
//No Sort
for (int i = 0; i < 3; i++)
{
printf("%d begine =%d,end =%d \n",i,StructArray[i].begin,StructArray[i].end);
}
//With begin small to big sort.注意Sizeof括号内的内容
qsort(StructArray, 3, sizeof(StructArray[0]), structCmp);
for (int i = 0; i < 3; i++)
{
printf(" sorted: %d begine =%d,end =%d \n", i, StructArray[i].begin, StructArray[i].end);
}
}