小白求助 谁能帮忙分析分析代码 结构体套二级指针
#define_CRT_SECURE_NO_WARNINGS#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*
"name1111"
"name2222"
"name3333"
*/
typedef struct Teacher
{
//char student
char name;
char *alisname;
char **stuname;
int age ;
int id;
}Teacher;
void printTeacher(Teacher *array, int num)
{
int i = 0;
for (i=0; i<num; i++)
{
printf("age:%d \n", array.age);
}
}
void sortTeacer(Teacher *array, int num)
{
int i,j;
Teacher tmp;
for (i=0; i<num; i++)
{
for (j=i+1; j<num; j++)
{
if (array.age > array.age)
{
tmp = array;//=号操作赋值操作
array = array;
array = tmp;
}
}
}
}
Teacher * createTeacher01(int num)
{
Teacher * tmp = NULL;
tmp = (Teacher *)malloc(sizeof(Teacher) * num); // Teacher Array
if (tmp == NULL)
{
return NULL;
}
return tmp; //
}
int createTeacher02(Teacher **pT, int num)
{
int i = 0, j = 0;
Teacher * tmp = NULL;
tmp = (Teacher *)malloc(sizeof(Teacher) * num); // Teacher Array
if (tmp == NULL)
{
return -1;
}
memset(tmp, 0, sizeof(Teacher) * num);
for (i=0; i<num; i++)
{
char **p = NULL;
//malloc一级指针
tmp.alisname = (char *)malloc(60);
//二级指针的第三种内存模型
p = (char **)malloc(3 * sizeof(char *));//打造二维内存
for (j=0; j<3; j++)
{
p = (char *)malloc(120);
}
tmp.stuname = p; //
}
*pT = tmp;//二级指针 形参 去间接的修改 实参 的值
return 0; //
}
void FreeTeacher(Teacher *p, int num)
{
int i = 0, j = 0;
if (p == NULL)
{
return;
}
for (i=0; i<num; i++)
{
//释放一级指针
if (p.alisname != NULL)
{
free(p.alisname);
}
//释放二级指针
if (p.stuname != NULL)
{
char **myp = p.stuname ;
for (j=0; j<3; j++)
{
if (myp != NULL)
{
free(myp);
}
}
free(myp);
p.stuname = NULL;
}
}
free(p);
}
void main()
{
int ret = 0;
int i = 0, j = 0;
//Teacher Array;//在stack 分配内存
int num = 3;
Teacher *pArray = NULL;
ret = createTeacher02(&pArray, num);
if (ret != 0)
{
printf("func createTeacher02() er:%d \n ", ret);
return ;
}
for (i=0; i<num; i++)
{
printf("\nplease enter age:");
scanf("%d", & (pArray.age) );
//printf("\nplease enter name:");
//scanf("%s",pArray.name ); //向指针所指的内存空间copy数据
printf("\nplease enter alias:");
scanf("%s",pArray.alisname );//向指针所指的内存空间copy数据
for (j=0; j<3; j++)
{
printf("please enter student name:");
scanf("%s",pArray.stuname );
}
}
//打印老师年龄
// for (i=0; i<num; i++)
// {
// printf("age:%d \n", Array.age);
// }
printTeacher(pArray, num);
sortTeacer(pArray, num);
printf("排序之后\n");
printTeacher(pArray, num);
FreeTeacher(pArray, num);
printf("hello...\n");
system("pause");
return ;
} F:\C语言\C提高视频\C提高day04_总结\文档\05_结构中套2级指针.bmp
页:
[1]