本文主要是介绍结构体中的一维,二维指针和内存的释放,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码:
/**
时间:2016.8.25 22:47
作者:一叶扁舟
作用:用来练习结构体即结构体的一维和二维指针
**/
#include "stdio.h"
#include "stdlib.h"
#include "string.h"typedef struct Teacher{//老师的年龄int age;//老师的名字char name[64];//老师的外号,别名char *s_name;//老师所带的学生的名字char** stuName;
}Teacher;//创建num个老师的对象
Teacher * creatTeacher(int teaNum,int stuNum){Teacher *teacher = (Teacher*)malloc(teaNum*sizeof(Teacher));if (teacher == NULL){return NULL;}//初始化for (int i = 0; i < teaNum; i++){memset(&teacher[i],0,sizeof(Teacher));// memset(teacher + 1, 0, sizeof(Teacher));//给s_name创建内存空间char *in_s_name= (char*)malloc(64 * sizeof(char));memset(in_s_name, 0, 64 * sizeof(char));teacher[i].s_name = in_s_name;{//给每一个老师带的学生名字创建二维空间char **p = (char**)malloc(stuNum*sizeof(char*));for (int j = 0; j < stuNum; j++){p[j] = (char*)malloc(64 * sizeof(char));//p[j]指向一个64*sizeof(char)的空间memset(p[j], 0, 64 * sizeof(char));}teacher[i].stuName = p;}}return teacher;
}
//释放二维指针
void freeSeconPoint(char **p, int num){for (int i = 0; i < num; i++){if (p[i] != NULL){ free(p[i]); }}free(p);
}//手动释放内存
void freeTeacher(Teacher *teacher,int teaNum,int stuNum){if (teacher == NULL){return;}//手动释放结构体中的一维指针(即释放的是一维指针指向的空间)for (int i = 0; i < teaNum; i++){char *s_name = teacher[i].s_name;//这个是错误的,因为这个不是指针,即分配的内存在栈中,这里面的东西是交个teacher统一释放//系统会拿着teacher的首地址统一的释放掉内存/**if (teacher[i].name != NULL){free(teacher[i].name);}*/if (s_name != NULL){free(s_name);}//手动释放二维指针if (teacher[i].stuName != NULL){freeSeconPoint(teacher[i].stuName, stuNum);}}if (teacher != NULL){free(teacher);teacher = NULL;}
}//输出所有老师的信息:
void printTeacher(Teacher *teacher, int teaNum, int stuNum){for (int i = 0; i < teaNum; i++){printf("\n老师的年龄:%d",teacher[i].age);printf("\n老师的名字:%s", teacher[i].name);printf("\n老师的别名:%s", teacher[i].s_name);printf("\n老师所带的学生:\n");for (int j = 0; j < stuNum; j++){printf("%s \t",teacher[i].stuName[j]);}printf("\n");}return;
}
void main(){//创建两个老师,每个老师带三个学生int teaNum = 2, stuNum = 3;Teacher *teacher = creatTeacher(teaNum, stuNum);if (teacher == NULL){return ;} for (int i = 0; i < teaNum; i++){char *in_s_name = teacher[i].s_name;printf("\n请输入老师的年龄:");scanf("%d",&(teacher[i].age));printf("\n请输入老师的名字:");scanf("%s",teacher[i].name);printf("\n请输入老师的别名:");scanf("%s", in_s_name);//老师所带学生的名字for (int j = 0; j < stuNum; j++){char **in_stuName = teacher[i].stuName;printf("\n请输入老师所带学生的名字:"); scanf("%s", in_stuName[j]);}}//输出结果printTeacher(teacher, teaNum, stuNum);//释放内存freeTeacher(teacher, teaNum, stuNum);system("pause");
}
效果截图:
这篇关于结构体中的一维,二维指针和内存的释放的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!