结构体中含有结构体指针
Posted 风的低吟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了结构体中含有结构体指针相关的知识,希望对你有一定的参考价值。
头文件:
#include<stdio.h> #include<stdlib.h> #include <string.h>
全局变量:
const int t_length = 2; int s_index = 5000; typedef struct Student{ int id; char name[64]; int age; }Student; typedef struct Teacher{ int id; char name[64]; int age; int s_num; Student *stu; }Teacher;
函数原型:
void createTeahcer(Teacher **ppt,int t_num);//为教师数组分配内存 void freeTeacher(Teacher *pt, int t_num); //释放内存 void sortStudent( Student * pt, int num ); //学生数组的排序 void sortTeacher(Teacher *pt, int num); //教师数组的排序 void printTeacher(Teacher *pt, int num); //遍历数组
实现方法:
void createTeahcer(Teacher **ppt,int t_num){ Teacher *temp; temp = (Teacher *)malloc(sizeof(Teacher) * t_num); *ppt = temp; } void freeTeacher(Teacher *pt, int t_num){ int i; if(pt != NULL){ for (i = 0; i < t_num; ++i){ if(pt[i].stu != NULL){ free(pt[i].stu); pt[i].stu = NULL; } } free(pt); } } void sortStudent( Student * pt, int num ) { int i, j; Student temp; for(i = 0; i < num; ++i){ for(j = i + 1; j < num; ++j){ if(pt[j].age < pt[i].age){ temp = pt[j]; pt[j] = pt[i]; pt[i] = temp; } } } } void sortTeacher(Teacher *pt, int num){ int i, j; Teacher temp; for(i = 0; i < num; ++i){ for(j = i + 1; j < num; ++j){ if(pt[j].age < pt[i].age){ temp = pt[j]; pt[j] = pt[i]; pt[i] = temp; } } sortStudent(pt[i].stu, pt[i].s_num); } } void printTeacher(Teacher *pt, int num){ int i, j = 0; Student stu; printf("\\n"); for(i = 0; i < num; ++i){ printf("学号:%d 姓名:%s 年龄:%d\\n", pt[i].id, pt[i].name, pt[i].age); for(j = 0; j < pt[i].s_num; ++j){ stu = (pt[i].stu)[j]; printf("第%d位学生 学号:%d 姓名:%s 年龄:%d\\n",j + 1, stu.id, stu.name, stu.age); } } }
测试:
int main(){ int i, j; Teacher *pt = NULL; createTeahcer(&pt, t_length); for(i = 0; i < t_length; ++i){ pt[i].id = i + 1002; printf("请输入第%d老师位的名字:", i + 1); scanf("%s",&(pt[i].name)); printf("请输入第%d位老师的年龄:", i + 1); scanf("%d", &(pt[i].age)); printf("请输入第%d位老师的所带学生的人数:", i + 1); scanf("%d", &(pt[i].s_num)); pt[i].stu = (Student *)malloc(sizeof(Student) * (pt[i].s_num)); //为老师所拥有的学生分配内存 for( j = 0; j < pt[i].s_num; ++j){ (pt[i].stu)[j].id = 5000 + s_index++; printf("请输入第%d位同学的名字:", j + 1); scanf("%s",&((pt[i].stu)[j].name)); printf("请输入第%d位同学的年龄:", j + 1); scanf("%d", &((pt[i].stu)[j].age)); } } sortTeacher(pt,t_length); printTeacher(pt, t_length); freeTeacher(pt, t_length); system("pause"); return 0; }
运行结果:
以上是关于结构体中含有结构体指针的主要内容,如果未能解决你的问题,请参考以下文章
C 语言结构体 ( 结构体中嵌套一级指针 | 分配内存时先 为结构体分配内存 然后再为指针分配内存 | 释放内存时先释放 指针成员内存 然后再释放结构头内存 )