#include <stdio.h>
#include <stdlib.h>
typedef struct _Teacher {
char name[100];
char *title;
int age;
char **p_stu; // 每个老师带的学生
} Teacher;
// 在堆区分配内存
Teacher *create_mem(int count)
{
Teacher *pt = NULL;
int i = 0, j = 0;
pt = (Teacher *)malloc(count*sizeof(Teacher));
// 为结构体的成员title(指针变量)开辟内存空间
for (i=0; i<count; i++){
pt[i].title = (char *)malloc(100);
// 为结构体的成员p_stu分配内存(二维数组)
char **tmp = (char **)malloc(3*sizeof(char *));
for (j=0; j<count; j++){
tmp[j] = (char *)malloc(100);
}
pt[i].p_stu = tmp;
}
return pt;
}
// 堆内存释放
int free_mem(Teacher *p, int count)
{
int i = 0, j = 0;
if (p == NULL)
return -1;
for (i=0; i<count; i++){
char **tmp = p[i].p_stu;
if (tmp == NULL){
continue;
}
for (j=0; j<count; j++){
if (tmp[j] != NULL){
free(tmp[j]);
}
}
free(tmp);
}
for (i=0; i<count; i++){
if (p[i].title != NULL)
free(p[i].title);
}
free(p);
}
// 打印结构体成员age
int print_t(Teacher *p, int count)
{
int i = 0, j = 0;
for (i=0; i<count; i++){
printf("%d: %d name: %s title: %s\n", i+1, p[i].age, p[i].name, p[i].title);
for (j=0; j<count; j++){
printf("%s ", p[i].p_stu[j]);
}
printf("\n");
}
return 0;
}
// 按照年龄对结构体进行排序
int sort_t(Teacher *p, int count)
{
int i = 0, j = 0;
Teacher tmp;
for (i=0; i<count; i++){
for (j=i+1; j<count; j++){
if (p[i].age > p[j].age){
tmp = p[i];
p[i] = p[j];
p[j] = tmp;
}
}
}
return 0;
}
int main_1(void)
{
Teacher t_arr[3];
int i = 0, count = 3, j = 0;
for (i=0; i<3; i++){
printf("请输入第%d位老师的年龄:", i+1);
scanf("%d", &t_arr[i].age);
printf("请输入第%d位老师的姓名:", i+1);
scanf("%s", t_arr[i].name);
for (j=0; j<3; j++){
printf("请输入第%d位老师的姓名:", j+1);
scanf("%s", t_arr[i].p_stu[j]);
}
}
printf("-----排序之前-----\n");
print_t(t_arr, count);
printf("-----排序之后-----\n");
sort_t(t_arr, count);
print_t(t_arr, count);
return 0;
}
int main(void)
{
Teacher *pt = NULL;
int i = 0, count = 3, j = 0;
pt = create_mem(count);
// 从键盘的输入为结构体赋值
for (i=0; i<3; i++){
printf("请输入第%d位老师的年龄:", i+1);
scanf("%d", &pt[i].age);
printf("请输入第%d位老师的姓名:", i+1);
scanf("%s", pt[i].name);
printf("请输入第%d位老师的职称:", i+1);
scanf("%s", pt[i].title);
for (j=0; j<3; j++){
printf("请输入第%d位学生的姓名", j+1);
scanf("%s", pt[i].p_stu[j]);
}
}
// 打印结构体
printf("-----排序之前-----\n");
print_t(pt, count);
printf("-----排序之后-----\n");
sort_t(pt, count);
print_t(pt, count);
free_mem(pt, count);
pt = NULL;
return 0;
}
结构体基础02
最新推荐文章于 2023-12-19 11:37:51 发布