结构体基础02
来源:互联网 发布:辽东学院网络教学平台 编辑:程序博客网 时间:2024/05/16 04:00
#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);}// 打印结构体成员ageint 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;}
0 0
- 结构体基础02
- 结构体基础
- 结构体基础
- 结构体基础
- C基础:结构体
- 结构体基础
- 结构体基础
- .NET基础--结构体
- 结构体基础
- 结构体基础知识点
- C结构体基础
- 结构体基础
- 1.1 struct 结构体 基础
- c语言基础-结构体
- C语言基础:结构体
- C++基础---结构体(struct)
- C语言基础-结构体
- C++基础之结构体
- p是一个大于3的素数,证明:7^p-6^p-1是43的倍数
- hdoj 3367 Pseudoforest(伪森林)
- OpenGL 渲染管线理论
- CodeForces#2A Winner
- java+JDBC链接MySQL数据库操作
- 结构体基础02
- 更改AlertView背景
- 【转】人生如梦游戏间,RPG游戏开源开发讲座(JAVA篇)[0]——月晕础润
- Linux Ubuntu基本
- 关于iOS开发中长按保存图片到相册
- BZOJ_P1925 [SDOI2010]地精部落(动态规划)
- EL表达式param隐含对象
- 博客第一天
- trie树