{4,1,"test4_1"},{5,1,"test5_1"},{6,1,"test6_1"},使用函数计算
时间: 2023-07-19 11:38:26 浏览: 36
如果要对这三个 Record 结构体按照 type 和 id 字段的大小进行排序,可以使用 qsort 函数,示例代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Record {
int id;
int type;
char data[16];
};
static int RecordCompare(const void *a, const void *b) {
const struct Record *pA = (const struct Record*)a;
const struct Record *pB = (const struct Record*)b;
if(pA->type!=pB->type)
return pA->type - pB->type;
else if (pA->id !=pB->id)
return pA->id - pB->id;
else
return 0;
}
int main() {
struct Record records[] = {
{4,1,"test4_1"},
{5,1,"test5_1"},
{6,1,"test6_1"}
};
int num_records = sizeof(records)/sizeof(records[0]);
qsort(records, num_records, sizeof(struct Record), RecordCompare);
for (int i=0; i<num_records; i++) {
printf("id: %d, type: %d, data: %s\n", records[i].id, records[i].type, records[i].data);
}
return 0;
}
```
输出结果为:
```
id: 4, type: 1, data: test4_1
id: 5, type: 1, data: test5_1
id: 6, type: 1, data: test6_1
```
可以看到,数组中的三个 Record 结构体按照 type 字段和 id 字段的大小依次进行了排序。