C语言通讯录排序:通信录的结构记录包括姓名、生日、电话号码,其中生日又包括年、月、日这三项。定义一个嵌套的结构类型,输入 n 个联系人的信息,再按他们的年龄从大到小的顺序依次输出其信息。试编写相应程序。
时间: 2024-02-03 22:13:42 浏览: 47
下面是C语言通讯录排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义生日结构体
struct birthday {
int year;
int month;
int day;
};
// 定义联系人结构体
struct contact {
char name[50];
struct birthday birthday;
char phone[20];
};
// 定义比较函数,按年龄从大到小排序
int cmp(const void *a, const void *b) {
struct contact *c1 = (struct contact *) a;
struct contact *c2 = (struct contact *) b;
int age1 = 2021 - c1->birthday.year;
int age2 = 2021 - c2->birthday.year;
return age2 - age1;
}
int main() {
int n;
printf("请输入联系人数量:");
scanf("%d", &n);
// 动态分配内存
struct contact *contacts = malloc(n * sizeof(struct contact));
if (contacts == NULL) {
printf("内存分配失败!");
return 1;
}
// 输入联系人信息
for (int i = 0; i < n; i++) {
printf("请输入第%d个联系人的信息:\n", i + 1);
printf("姓名:");
scanf("%s", contacts[i].name);
printf("生日(年 月 日):");
scanf("%d %d %d", &contacts[i].birthday.year, &contacts[i].birthday.month, &contacts[i].birthday.day);
printf("电话号码:");
scanf("%s", contacts[i].phone);
}
// 排序
qsort(contacts, n, sizeof(struct contact), cmp);
// 输出排序后的联系人信息
printf("按年龄从大到小排序后的联系人信息:\n");
for (int i = 0; i < n; i++) {
printf("%s\t%d-%02d-%02d\t%s\n", contacts[i].name, contacts[i].birthday.year, contacts[i].birthday.month,
contacts[i].birthday.day, contacts[i].phone);
}
// 释放内存
free(contacts);
return 0;
}
```
代码中使用了结构体的嵌套,定义了生日结构体和联系人结构体。使用了 `qsort` 函数进行排序,其中 `cmp` 函数为比较函数,按照年龄从大到小排序。最后输出排序后的联系人信息。
注意,在动态分配内存时,需要使用 `malloc` 函数,并且在使用完后需要使用 `free` 函数释放内存。