#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "string.h"
查找字符在数组中出现的位置
//void Search_Str_Pos(const char *table[], const int size,char *str, int *pos)
//{
// char **temp;
// int i = 0;
// int positon = -1;
// if (table == NULL || str == NULL || pos == NULL)
// {
// return;
// }
// temp = table;
// for (i = 0; i < size; i++)
// {
// if (strcmp(temp[i], str) == 0)
// {
// positon = i;
// }
// }
// *pos = positon;
//}
//#define DIM(a) (sizeof(a)/sizeof(*a))
typedef struct
{
char *alisname;
char **tname;
int age;
int id;
}Teacher;
void Free_Teacher_Mem1(Teacher * p, int num)
{
int i = 0;
int j = 0;
if (p == NULL)
return;
for (i = 0; i < num; i++)
{
if (p[i].alisname != NULL)
{
free(p[i].alisname);
p[i].alisname = NULL;
}
}
for (i = 0; i < num; i++)
{
if (p[i].tname == NULL)
return;
for (j = 0; j < 3; j++)
{
if (p[i].tname[j] != NULL)
{
free(p[i].tname[j]);
}
}
if (p[i].tname != NULL)
{
free(p[i].tname);
}
}
free(p);
p = NULL;
}
// 创建老师的内存空间 p代表传入的指针地址,num代表老师人数
int Create_Teacher(Teacher **p, int num)
{
Teacher *temp_Teacher;
char **temp=NULL;
int ret_flag = 0;
int i = 0;
int j = 0;
temp_Teacher = (Teacher *)malloc(sizeof(Teacher)*num);
// 如果为NULL,代表内存空间不足
if (temp_Teacher == NULL)
{
ret_flag = - 1;
goto END;
}
for (i = 0; i < num; i++)
{
temp_Teacher[i].alisname = (char *)malloc(sizeof(char)* 60);
if (temp_Teacher[i].alisname == NULL)
{
ret_flag = -1;
goto END;
}
temp = (char **)malloc(sizeof(char *)* 3);
for (j = 0; j < 3; j++)
{
temp[j] = (char *)malloc(sizeof(char)* 60);
if (temp[j] == NULL)
{
ret_flag = -1;
goto END;
}
}
temp_Teacher[i].tname = temp;
}
END:
if (ret_flag == -1)
{
Free_Teacher_Mem1(temp_Teacher, num);
}
else
{
*p = temp_Teacher;
}
}
void Print_Teacher(Teacher *p,int num)
{
int i = 0;
int j = 0;
for (i = 0; i < num; i++)
{
for (j = 0; j < 3;j++)
printf("%s\n", p[i].tname[j]);
}
}
void main()
{
int num = 1;
Teacher *p =NULL;
int i = 0;
int j = 0;
Create_Teacher(&p, num);
for (i = 0; i < num; i++)
{
printf("请输入姓名:\n");
for (j = 0; j < 3;j++)
scanf("%s", p[i].tname[j]);
}
Print_Teacher(p, num);
Free_Teacher_Mem1(p, num);
}
结构体套二级指针.c
最新推荐文章于 2021-08-09 00:51:08 发布